依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
<scope>compile</scope>
</dependency>
工具类
import org.apache.poi.hssf.usermodel.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class ExcelUtils {
/*title 标题 headers 头列属性 list为数据集合 out 输入流*/
public static boolean exportMessageExcelFile(String title, String[] headers, List dossierList, OutputStream out)
{
boolean flag = true;
// 声明一个工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = workbook.createSheet(title);
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth((short) 15);
//产生表格标题行
HSSFRow row = sheet.createRow(0);
for (short i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
for(int i = 0; i< dossierList.size();i++)
{
Object obj = (Object) dossierList.get(i);
row = sheet.createRow(i+1);//创建第1行
for (int j = 0; j < headers.length; j++) {
HSSFCell cell = row.createCell(j);//创建第一行的第一个属性列
cell.setCellStyle(style);
switch (j){
//根据你头定义的表格样式填充具体数据
case 0:
cell.setCellValue(obj.getBuyerNo());
break;
case 1:
cell.setCellValue(obj.UserName());
break;
case 2:
cell.setCellValue(obj.getVirtualAccountNo());
break;
case 3:
cell.setCellValue(obj.getExpiryDate());
break;
case 4:
cell.setCellValue(DateUtil.formatDate(obj.getCreateDate(),"yyyy-MM-dd hh:mm:ss"));
break;
case 5:
cell.setCellValue(obj.getSpendLimitAmount());
break;
}
}
}
try {
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
flag = false;
}finally {
//清理资源
try {
if(out != null)
{
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return flag;
}