Excel文件导出
excel导出xls、csv格式的list对象
1.Excel文件工具类
public class ExcelUtils {
private static String sheetName = "清结算";
public static void write(HttpServletResponse response, HttpServletRequest request,
List<TransctionInfoDto> lists,String fileName){
//excel标题
String rows[] = {"id","商品名称","交易金额","创建日期","修改日期"};
List<String> rowsTitle = Arrays.asList(rows);
//excel文件名
if(StringUtils.isEmpty(fileName)){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
String files = sdf.format(date);
fileName = files+".xls";
}
SXSSFWorkbook workbook = new SXSSFWorkbook(lists.size());
//SXSSFSheet sheet = workbook.createSheet(fileName.substring(0,fileName.indexOf(".xls")));
SXSSFSheet sheet = workbook.createSheet(sheetName);
Integer rowIndex = 1;
Integer titleIndex = 0;
Row row = null;
Cell cell = null;
row = sheet.createRow(titleIndex);
for(String title:rowsTitle){
cell = row.createCell(titleIndex++);
cell.setCellValue(title);
}
for(TransctionInfoDto rowData: lists ){
row = sheet.createRow(rowIndex++);
cell = row.createCell(0);
cell.setCellValue(rowData.getId());
cell = row.createCell(1);
cell.setCellValue(rowData.getBankName());
cell = row.createCell(2);
cell.setCellValue(rowData.getBankCard());
cell = row.createCell(3);
cell.setCellValue(rowData.getCreateTime());
cell = row.createCell(4);
cell.setCellValue(rowData.getUpdateTime());
}
pwrite(response,workbook,fileName);
}
private static void pwrite(HttpServletResponse response, Workbook workbook, String fileName){
response.setCharacterEncoding("UTF-8");
response.setContentType("application/ms-excel;charset=UTF-8");
try {
response.addHeader("Content-Disposition", "attachment; filename="+new String(fileName.getBytes("UTF-8"),"UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
fileName= UUID.randomUUID().toString()+".xls";
response.addHeader("Content-Disposition", "attachment; filename="+fileName);
}
try {
workbook.write(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
}