Browse Source

支持通过模板填充数据

pull/635/head
Jiaju Zhuang 5 years ago
parent
commit
d2c8d205de
  1. 12
      src/main/java/com/alibaba/excel/ExcelWriter.java
  2. 1
      src/main/java/com/alibaba/excel/util/WorkBookUtil.java
  3. 8
      src/main/java/com/alibaba/excel/write/ExcelBuilder.java
  4. 62
      src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java
  5. 8
      src/main/java/com/alibaba/excel/write/builder/ExcelWriterSheetBuilder.java
  6. 16
      src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java
  7. 15
      src/test/java/com/alibaba/easyexcel/test/core/fill/FillData.java
  8. 90
      src/test/java/com/alibaba/easyexcel/test/core/fill/FillDataTest.java
  9. 69
      src/test/java/com/alibaba/easyexcel/test/temp/poi/PoiTest.java
  10. BIN
      src/test/resources/fill/simple.xlsx

12
src/main/java/com/alibaba/excel/ExcelWriter.java

@ -155,6 +155,18 @@ public class ExcelWriter {
return this;
}
/**
* Fill value to a sheet
*
* @param data
* @param writeSheet
* @return
*/
public ExcelWriter fill(Object data, WriteSheet writeSheet) {
excelBuilder.fill(data, writeSheet);
return this;
}
/**
* Write data to a sheet
*

1
src/main/java/com/alibaba/excel/util/WorkBookUtil.java

@ -37,6 +37,7 @@ public class WorkBookUtil {
// When using SXSSFWorkbook, you can't get the actual last line.But we need to read the last line when we
// are using the template, so we cache it
if (xssfWorkbook != null) {
writeWorkbookHolder.setXssfWorkbook(xssfWorkbook);
for (int i = 0; i < xssfWorkbook.getNumberOfSheets(); i++) {
writeWorkbookHolder.getTemplateLastRowMap().put(i, xssfWorkbook.getSheetAt(i).getLastRowNum());
}

8
src/main/java/com/alibaba/excel/write/ExcelBuilder.java

@ -35,6 +35,14 @@ public interface ExcelBuilder {
*/
void addContent(List data, WriteSheet writeSheet, WriteTable writeTable);
/**
* WorkBook fill value
*
* @param data
* @param writeSheet
*/
void fill(Object data, WriteSheet writeSheet);
/**
* Creates new cell range. Indexes are zero-based.
*

62
src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java

@ -2,12 +2,13 @@ package com.alibaba.excel.write;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@ -15,7 +16,6 @@ import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
@ -109,6 +109,7 @@ public class ExcelBuilderImpl implements ExcelBuilder {
}
}
@Override
public void fill(Object data, WriteSheet writeSheet) {
try {
if (context.writeWorkbookHolder().getTemplateFile() == null
@ -127,17 +128,14 @@ public class ExcelBuilderImpl implements ExcelBuilder {
}
private void doFill(Object data) {
BeanMap beanMap = BeanMap.create(data);
WriteSheetHolder writeSheetHolder = context.writeSheetHolder();
Sheet sheet = writeSheetHolder.getSheet();
Map<Integer, Integer> templateLastRowMap = context.writeWorkbookHolder().getTemplateLastRowMap();
if (!templateLastRowMap.containsKey(writeSheetHolder.getSheetNo())) {
if (sheet == null) {
throw new ExcelGenerateException(
"The corresponding table cannot be found,sheetNo:" + writeSheetHolder.getSheetNo());
}
Map<String, AnalysisCell> analysisCellMap = new HashMap<String, AnalysisCell>(16);
List<AnalysisCell> analysisCellList = new ArrayList<AnalysisCell>();
for (int i = 0; i < templateLastRowMap.get(writeSheetHolder.getSheetNo()); i++) {
Row row = sheet.getRow(i);
for (int j = 0; j < row.getLastCellNum(); j++) {
@ -150,29 +148,49 @@ public class ExcelBuilderImpl implements ExcelBuilder {
List<String> variableList = new ArrayList<String>();
analysisCell.setVariableList(variableList);
boolean matches = true;
int index = 0;
while (matches) {
Matcher matcher = FILL_PATTERN.matcher(value);
String variable = value.substring(matcher.start(), matcher.end());
variableList.add(variable);
value = matcher.replaceFirst("{" + index++ + "}");
matches = FILL_PATTERN.matcher(value).matches();
analysisCellList.add(analysisCell);
}
}
}
}
if (CollectionUtils.isEmpty(data)) {
return;
}
WriteSheetHolder writeSheetHolder = context.writeSheetHolder();
int newRowIndex = writeSheetHolder.getNewRowIndexAndStartDoWrite();
if (writeSheetHolder.isNew() && !writeSheetHolder.getExcelWriteHeadProperty().hasHead()) {
newRowIndex += context.currentWriteHolder().relativeHeadRowIndex();
if (data instanceof Collection) {
} else if (data instanceof Map) {
} else {
}
// BeanMap is out of order,so use fieldList
List<Field> fieldList = new ArrayList<Field>();
for (int relativeRowIndex = 0; relativeRowIndex < data.size(); relativeRowIndex++) {
int n = relativeRowIndex + newRowIndex;
addOneRowOfDataToExcel(data.get(relativeRowIndex), n, relativeRowIndex, fieldList);
BeanMap beanMap = BeanMap.create(data);
for (AnalysisCell analysisCell : analysisCellList) {
Cell cell = sheet.getRow(analysisCell.getRowIndex()).getCell(analysisCell.getColumnIndex());
if (analysisCell.getVariableList().size() == 1) {
Object value = beanMap.get(analysisCell.getVariableList().get(0));
if (value == null) {
continue;
}
converterAndSet(writeSheetHolder, value.getClass(), cell, value, null);
} else {
List<String> fileDataStringList = new ArrayList<String>();
for (String variable : analysisCell.getVariableList()) {
Object value = beanMap.get(variable);
CellData cellData = convert(writeSheetHolder, String.class, cell, value, null);
String fillDataString = cellData.getStringValue();
if (fillDataString == null) {
fillDataString = "";
}
fileDataStringList.add(fillDataString);
}
cell.setCellValue(String.format(analysisCell.getPrepareData(), fileDataStringList));
}
}
}

8
src/main/java/com/alibaba/excel/write/builder/ExcelWriterSheetBuilder.java

@ -135,6 +135,14 @@ public class ExcelWriterSheetBuilder {
excelWriter.finish();
}
public void doFill(Object data) {
if (excelWriter == null) {
throw new ExcelGenerateException("Must use 'EasyExcelFactory.write().sheet()' to call this method");
}
excelWriter.fill(data, build());
excelWriter.finish();
}
public ExcelWriterTableBuilder table() {
return table(null);
}

16
src/main/java/com/alibaba/excel/write/metadata/holder/WriteWorkbookHolder.java

@ -10,6 +10,7 @@ import java.util.HashMap;
import java.util.Map;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -24,12 +25,15 @@ import com.alibaba.excel.write.metadata.WriteWorkbook;
* @author Jiaju Zhuang
*/
public class WriteWorkbookHolder extends AbstractWriteHolder {
private static final Logger LOGGER = LoggerFactory.getLogger(WriteWorkbookHolder.class);
/***
* poi Workbook
*/
private Workbook workbook;
/**
* When reading version 07 with the template, the <code>workbook</code> cannot get the specific line number, so it
* needs to get the specific line number.
*/
private XSSFWorkbook xssfWorkbook;
/**
* current param
*/
@ -130,6 +134,14 @@ public class WriteWorkbookHolder extends AbstractWriteHolder {
this.workbook = workbook;
}
public XSSFWorkbook getXssfWorkbook() {
return xssfWorkbook;
}
public void setXssfWorkbook(XSSFWorkbook xssfWorkbook) {
this.xssfWorkbook = xssfWorkbook;
}
public Map<Integer, WriteSheetHolder> getHasBeenInitializedSheet() {
return hasBeenInitializedSheet;
}

15
src/test/java/com/alibaba/easyexcel/test/core/fill/FillData.java

@ -0,0 +1,15 @@
package com.alibaba.easyexcel.test.core.fill;
import com.alibaba.excel.annotation.format.NumberFormat;
import lombok.Data;
/**
* @author Jiaju Zhuang
*/
@Data
public class FillData {
private String name;
@NumberFormat("0#")
private double number;
}

90
src/test/java/com/alibaba/easyexcel/test/core/fill/FillDataTest.java

@ -0,0 +1,90 @@
package com.alibaba.easyexcel.test.core.fill;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import com.alibaba.easyexcel.test.core.style.StyleData;
import com.alibaba.easyexcel.test.core.style.StyleDataListener;
import com.alibaba.easyexcel.test.util.TestFileUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.LoopMergeStrategy;
import com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.AbstractVerticalCellStyleStrategy;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.alibaba.excel.write.style.row.SimpleRowHeightStyleStrategy;
/**
*
* @author Jiaju Zhuang
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class FillDataTest {
private static File file07;
private static File file03;
private static File simpleTemplate07;
@BeforeClass
public static void init() {
file07 = TestFileUtil.createNewFile("fill07.xlsx");
file03 = TestFileUtil.createNewFile("fill03.xls");
simpleTemplate07 = TestFileUtil.readFile("fill" + File.separator + "simple.xlsx");
}
@Test
public void t01Fill07() {
fill(file07);
}
@Test
public void t02Fill03() {
fill(file03);
}
private void fill(File file) {
FillData fillData = new FillData();
fillData.setName("张三");
fillData.setNumber(5.2);
EasyExcel.write(file).withTemplate(simpleTemplate07).sheet().doFill(fillData);
}
private List<StyleData> data() {
List<StyleData> list = new ArrayList<StyleData>();
StyleData data = new StyleData();
data.setString("字符串0");
data.setString1("字符串01");
StyleData data1 = new StyleData();
data1.setString("字符串1");
data1.setString1("字符串11");
list.add(data);
list.add(data1);
return list;
}
private List<StyleData> data10() {
List<StyleData> list = new ArrayList<StyleData>();
for (int i = 0; i < 10; i++) {
StyleData data = new StyleData();
data.setString("字符串0");
data.setString1("字符串01");
list.add(data);
}
return list;
}
}

69
src/test/java/com/alibaba/easyexcel/test/temp/poi/PoiTest.java

@ -1,8 +1,12 @@
package com.alibaba.easyexcel.test.temp.poi;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
@ -49,4 +53,69 @@ public class PoiTest {
xssfSheet.createRow(20);
LOGGER.info("一共行数:{}", xssfSheet.getLastRowNum());
}
@Test
public void lastRowNum233() throws IOException {
String file = TestFileUtil.getPath() + "fill" + File.separator + "simple.xlsx";
Workbook xx=new XSSFWorkbook(file);
SXSSFWorkbook xssfWorkbook = new SXSSFWorkbook();
Sheet xssfSheet = xssfWorkbook.getXSSFWorkbook().getSheetAt(0);
Cell cell = xssfSheet.getRow(0).createCell(9);
cell.setCellValue("testssdf是士大夫否t");
FileOutputStream fileout = new FileOutputStream("d://test/r2" + System.currentTimeMillis() + ".xlsx");
xssfWorkbook.write(fileout);
xssfWorkbook.close();
}
@Test
public void lastRowNum2332222() throws IOException {
String file = TestFileUtil.getPath() + "fill" + File.separator + "simple.xlsx";
Workbook xx=new XSSFWorkbook(file);
SXSSFWorkbook xssfWorkbook = new SXSSFWorkbook();
Sheet xssfSheet = xssfWorkbook.getXSSFWorkbook().getSheetAt(0);
Cell cell = xssfSheet.getRow(0).createCell(9);
cell.setCellValue("testssdf是士大夫否t");
FileOutputStream fileout = new FileOutputStream("d://test/r2" + System.currentTimeMillis() + ".xlsx");
xssfWorkbook.write(fileout);
}
@Test
public void lastRowNum23443() throws IOException {
String file = TestFileUtil.getPath() + "fill" + File.separator + "simple.xlsx";
SXSSFWorkbook xssfWorkbook = new SXSSFWorkbook(new XSSFWorkbook(file));
Sheet xssfSheet = xssfWorkbook.getSheetAt(0);
FileOutputStream fileout = new FileOutputStream("d://test/r2" + System.currentTimeMillis() + ".xlsx");
xssfWorkbook.write(fileout);
xssfWorkbook.close();
}
@Test
public void lastRowNum2() throws IOException {
String file = TestFileUtil.getPath() + "fill" + File.separator + "simple.xlsx";
SXSSFWorkbook xssfWorkbook = new SXSSFWorkbook(new XSSFWorkbook(file));
Sheet xssfSheet = xssfWorkbook.getXSSFWorkbook().getSheetAt(0);
LOGGER.info("一共行数:{}", xssfSheet.getPhysicalNumberOfRows());
LOGGER.info("一共行数:{}", xssfSheet.getLastRowNum());
LOGGER.info("一共行数:{}", xssfSheet.getFirstRowNum());
}
@Test
public void lastRowNumXSSF2() throws IOException {
String file = TestFileUtil.getPath() + "fill" + File.separator + "simple.xlsx";
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(file);
LOGGER.info("一共:{}个sheet", xssfWorkbook.getNumberOfSheets());
XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
LOGGER.info("一共行数:{}", xssfSheet.getLastRowNum());
XSSFRow row = xssfSheet.getRow(0);
LOGGER.info("第一行数据:{}", row);
}
}

BIN
src/test/resources/fill/simple.xlsx

Binary file not shown.
Loading…
Cancel
Save