1、直接是工具类调用静态方法
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class MatchDtoToExcel {
/**
*
* @param xls
* MatchInfo实体类的一个对象
* @throws Exception
* 在导入Excel的过程中抛出异常
*/
public static void MatchInfo2Excel(List<MatchInfo> xls, String fileName) throws Exception {
// 获取总列数
int CountColumnNum = 7;
// 创建Excel文档
HSSFWorkbook hwb = new HSSFWorkbook();
MatchInfo matchInfo = null;
// sheet 对应一个工作页
HSSFSheet sheet = hwb.createSheet("pldrxkxxmb");
HSSFRow firstrow = sheet.createRow(0); // 下标为0的行开始
HSSFCell[] firstcell = new HSSFCell[CountColumnNum];
String[] names = new String[CountColumnNum];
names[0] = "序号";
names[1] = "一号店商品ID";
names[2] = "一号店商品编号";
names[3] = "一号店商品名";
names[4] = "条形码";
names[5] = "竞争对手商品编码";
names[6] = "竞争对手商品名";
for (int j = 0; j < CountColumnNum; j++) {
firstcell[j] = firstrow.createCell(j);
firstcell[j].setCellValue(new HSSFRichTextString(names[j]));
}
for (int i = 0; i < xls.size(); i++) {
// 创建一行
HSSFRow row = sheet.createRow(i + 1);
// 得到要插入的每一条记录
matchInfo = xls.get(i);
if (matchInfo == null) {
System.out.println("数据库导出成功");
}
for (int colu = 0; colu <= 8; colu++) {
// 在一行内循环
HSSFCell x1 = row.createCell(0);
x1.setCellValue(matchInfo.getId());
HSSFCell x2 = row.createCell(1);
x2.setCellValue(matchInfo.getProductId());
HSSFCell x3 = row.createCell(2);
x3.setCellValue(matchInfo.getProductCode());
HSSFCell x4 = row.createCell(3);
x4.setCellValue(matchInfo.getProductName());
HSSFCell x5 = row.createCell(4);
x5.setCellValue(matchInfo.getScriptCode());
HSSFCell x6 = row.createCell(5);
x6.setCellValue(matchInfo.getOpponProductCode());
HSSFCell x7 = row.createCell(6);
x7.setCellValue(matchInfo.getOpponProductName());
}
}
// 创建文件输出流,准备输出电子表格
OutputStream out = new FileOutputStream(fileName+".xls");
hwb.write(out);
out.close();
System.out.println("数据库导出成功");
}
}
多的不说看代码