-
这是网上看到一个博主也提出了这个问题,我也出现了这个问题: https://blog.csdn.net/weixin_40199949/article/details/100014405
-
建议直接使用工具类(源码的注释是中文的绝对给力)来做任何导出excel的操作,避免出现不必要的坑。
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.7</version>
</dependency>
- 问题是循环的时候创建的样式是有限的,解决的办法是先创建好样式再设置样式(看我下方的注释)。
import cn.hutool.poi.excel.RowUtil;
import cn.hutool.poi.excel.StyleSet;
import cn.hutool.poi.excel.cell.CellUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public static void main(String[] args) throws IOException {
collapseRow();
}
private static void collapseRow() throws IOException {
try (SXSSFWorkbook workbook = new SXSSFWorkbook(100)) {
SXSSFSheet sheet = workbook.createSheet();
//提前创建好样式,如果你在for循环内设置样式的话,样式对象是有限的会导致有些样式缺失但不报错的问题。一定要注意!!!!
StyleSet styleSet = new StyleSet(workbook);
CellStyle cellStyle = styleSet.getCellStyle();
for (int i = 0; i < 10; i++) {
Row row = RowUtil.getOrCreateRow(sheet, i);
for (int j = 0; j < 20; j++) {
Cell cell = CellUtil.getOrCreateCell(row, j);
//在这里设置样式,这样就不会出现因为循环创建而导致部分单元格缺失的问题。
CellUtil.setCellValue(cell, j, cellStyle);
}
}
try (FileOutputStream fileOut = new FileOutputStream("gideonYeung.xlsx")) {
workbook.write(fileOut);
System.out.println("导出成功。");
} finally {
workbook.dispose();
}
}
}