package com.liujue.util.excel;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
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.XSSFWorkbook;
public class WriteExcel {
public String file_pathname = "";
private Workbook workbook = null;
public List<String> titlerow = null;
//创建对象时自动创建工作簿
public WriteExcel() throws Exception {
workbook = new XSSFWorkbook();
}
public WriteExcel(String file_pathname) throws Exception {
this.file_pathname = file_pathname;
workbook = new XSSFWorkbook();
}
//创建无数据的工作表,并返回表对象
public Sheet CreateSheet() throws Exception {
Sheet sheet = this.workbook.createSheet();
return sheet;
}
//串讲有数据的工作表,并返回表对象
public Sheet CreateSheet(List<List<String>> sheetdata) throws Exception {
Sheet sheet = this.workbook.createSheet();
if(this.titlerow != null)
sheetdata.add(0, this.titlerow);
for(int row = 0;row < sheetdata.size();row++) {
Row rows = sheet.createRow(row);
for(int col = 0;col < sheetdata.get(row).size();col++) {
rows.createCell(col).setCellValue(sheetdata.get(row).get(col));
}
}
return sheet;
}
public void SaveToFile(String filename) throws Exception {
this.file_pathname = filename;
this.SaveToFile();
}
public void SaveToFile() throws Exception {
File xfile = new File(this.file_pathname);
if (!xfile.exists())
xfile.createNewFile();
FileOutputStream xstream = new FileOutputStream(xfile);
this.workbook.write(xstream);
this.workbook.close();
xstream.flush();
xstream.close();
}
}
poi写入excel并生成文件
最新推荐文章于 2023-05-18 23:10:58 发布