当导出的excel 数据很多时,导出到模板的数据怎么自动创建多个sheet ,并导出到多个sheet中,
我是使用了模板,导出数据到excel 里,但是不知道,怎么分sheet.,肯能很麻烦,知道的哥哥姐姐迪迪妹妹,可以告诉我,感谢
java操作Excel的工具POI中有创建Sheet的方法的,查下API,对着需求调用就行了。
给你断代码看看吧,你可以得到sheet的list,然后把你的内容循环进去就ok
package com.yixin.js.utils.jxl;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
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.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.yixin.js.base.util.StringUtil;
import com.yixin.js.utils.LogUtil;
public class PoiExportUtil {
private static final int ColumnWidth = 6350;
public static void exportExcelWithStyle(ExcelVo excelVo, OutputStream out) {
if (excelVo == null) {
throw new java.lang.IllegalArgumentException("参数不能为空!");
}
Workbook book = null;
try {
book = new XSSFWorkbook();
List sheetVo = excelVo.getSheetList();
if(sheetVo==null){
throw new java.lang.IllegalArgumentException("Excel表中没有数据!");
}
//每一个sheet表
for(int i=0;i<sheetVo.size();i++){
SheetVo sv = sheetVo.get(i);
Sheet sheet =book.createSheet(sv.getName());
List<Object[]> listRow =sv.getListRow();
List<short[]> listCellFormat = sv.getListCellFormat();
List<Object> title = sv.getTitle();
//每一行
Row rowTitle = sheet.createRow(0);
//标题数据
for(int c=0;c<title.size();c++){
//单元格宽度
if(!StringUtil.isEmpty(title.get(c)+"")){
sheet.setColumnWidth(c, PoiExportUtil.ColumnWidth);
}
Cell cell = rowTitle.createCell(c);
if(!StringUtil.isEmpty(title.get(c)+"")){
cell.setCellValue((String)title.get(c));
}else{
cell.setCellValue("");
}
}
//行数据
for(int r=0;r<listRow.size();r++){
//每行的样式数组
short[] cellFormat = null;
if(listCellFormat.size()>r){
cellFormat =listCellFormat.get(r);
}
Object[] ob = listRow.get(r);
Row row = sheet.createRow(r+1);
for(int c = 0;c<ob.length;c++){
Cell cell=row.createCell(c);
cell.setCellValue(ob[c]+"");
//如果为空则设置为空字符串
if(ob[c]==null){
cell.setCellValue("");
}
if(cellFormat==null){
continue;
}
//添加样式,cellFormat长度大于c并且不能为空
if(cellFormat.length>c && cellFormat[c]!=0){
XSSFCellStyle style = (XSSFCellStyle) book.createCellStyle();
//图案填充样式,此处为实体
style.setFillPattern(CellStyle.SOLID_FOREGROUND );
//前景色
style.setFillForegroundColor(cellFormat[c]);
//图案背景色
// style.setFillBackgroundColor(IndexedColors.RED.getIndex());
cell.setCellStyle(style);
}
}
}
}
book.write(out);
} catch (Exception e) {
e.printStackTrace();
LogUtil.error(e.getMessage());
}finally{
if(out!=null)
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}