/**
* 将list中数据转化成excel表格
*
* @param data
* list数据
* @param headers
* 表格的表头
* @return String 表格存储路径
* @author 邢艳芬
*/
public static String generateBillsExcel(List data, List<String> headers,
Timestamp startTime, Timestamp endTime) {
// 判断目录是否存在,不存在则创建,存在则继续
File file = new File(PATH_EXCEL);
// 判断文件是否已经创建
if (!file.exists()) {
// 删除已经创建的文件
file.mkdirs();
}
String fileName = PATH_EXCEL + System.currentTimeMillis() + ".xls";
// 声明一个工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = workbook.createSheet("orderBills");
// 设置表格默认列宽度为20个字节
sheet.setDefaultColumnWidth(20);
// 生成一个样式
HSSFCellStyle style = workbook.createCellStyle();
// 设置这些样式
style.setFillForegroundColor(HSSFColor.GOLD.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 生成一个字体
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.BLACK.index);
// font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样式
style.setFont(font);
// 指定当单元格内容显示不下时自动换行
style.setWrapText(true);
FileOutputStream out = null;
try {
//合并单元格,写标题 new Region 中地一个参数,合并行起始行号,第二个参数起始列号,第三个参数结束行号,第四个参数结束列号
sheet.addMergedRegion(new Region(0, (short) 0, 0, (short) (headers
.size() - 1)));
HSSFRow row0 = sheet.createRow(0);
HSSFCell cell0 = row0.createCell(0);
cell0.setCellStyle(style);
//写表格总结数据这里写的是表格内容日期
HSSFRichTextString text0 = new HSSFRichTextString("日期:"
+ DataConverter.TimeToString(startTime) + " ~ "
+ DataConverter.TimeToString(endTime));
cell0.setCellValue(text0);
// 产生表格标题行
HSSFRow row = sheet.createRow(1);
for (int i = 0; i < headers.size(); i++) {
HSSFCell cell1 = row.createCell(i);
cell1.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(
(String) headers.get(i));
cell1.setCellValue(text);
}
// 遍历集合数据,产生数据行
if (null != data && !data.isEmpty()) {
for (int rowIndex = 0; rowIndex < data.size(); rowIndex++) {
row = sheet.createRow(rowIndex + 2);
Object rowData = data.get(rowIndex);
for (int cellIndex = 0; cellIndex < headers.size(); cellIndex++) {
HSSFCell cell = row.createCell(cellIndex);
String cellStr = "";
if (rowData instanceof OrderBills) {
cellStr = getOrderBillsCellValue(
headers.get(cellIndex),
(OrderBills) rowData);
}
HSSFRichTextString richString = new HSSFRichTextString(
cellStr == null ? null : cellStr);
cell.setCellValue(richString);
}
}
}
out = new FileOutputStream(fileName);
workbook.write(out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return fileName;
}
java生成excel表格(List)
最新推荐文章于 2023-03-02 14:18:15 发布