生成XLSX格式Excel文檔
- 使用Apache POI導(dǎo)出Excel小結(jié)--導(dǎo)出XLS格式文檔
- 使用Apache POI導(dǎo)出Excel小結(jié)--導(dǎo)出XLSX格式文檔
- 使用Apache POI導(dǎo)出Excel--大數(shù)量導(dǎo)出
上一篇我們已經(jīng)給出不同版本Excel文檔處理的數(shù)據(jù)信息意述,下來我們繼續(xù)再看一看如何生成XLSX格式Excel文檔提佣。
使用于小數(shù)據(jù)量生成
- 基于Excel模板寫入數(shù)據(jù)會引發(fā)內(nèi)存溢出
注意:
- 以下代碼少ReportInternalException大家可以忽略(我們封裝的一個異常類)
- 導(dǎo)出的Excel同時考慮到數(shù)據(jù)的本身類型,如整數(shù)荤崇、小數(shù)拌屏、日期等
- 第一種寫入數(shù)據(jù)方式[writeExcel]方法為直接寫入數(shù)據(jù)
- 第二種寫入數(shù)據(jù)方式需依次調(diào)用方法[writeExcelTitle、writeExcelData]术荤,先完成寫入Excel標(biāo)題與列名倚喂,再完成數(shù)據(jù)寫入(或者說基于模板方式寫入數(shù)據(jù))
- 第二種方式有內(nèi)存溢出的可能性
- 我們使用[styleMap]方法避免重復(fù)創(chuàng)建Excel單元格樣式(否則受Excel創(chuàng)建樣式數(shù)量限制)
繼續(xù)開始曬代碼
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import javax.imageio.ImageIO;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Excel 相關(guān)操作類(小數(shù)據(jù)量寫入<=60000)
*/
public class Excel2007Utils {
private static final int DEFAULT_COLUMN_SIZE = 30;
/**
* 斷言Excel文件寫入之前的條件
*
* @param directory 目錄
* @param fileName 文件名
* @return file
* @throws IOException
*/
private static File assertFile(String directory, String fileName) throws IOException {
File tmpFile = new File(directory + File.separator + fileName + ".xlsx");
if (tmpFile.exists()) {
if (tmpFile.isDirectory()) {
throw new IOException("File '" + tmpFile + "' exists but is a directory");
}
if (!tmpFile.canWrite()) {
throw new IOException("File '" + tmpFile + "' cannot be written to");
}
} else {
File parent = tmpFile.getParentFile();
if (parent != null) {
if (!parent.mkdirs() && !parent.isDirectory()) {
throw new IOException("Directory '" + parent + "' could not be created");
}
}
}
return tmpFile;
}
/**
* 日期轉(zhuǎn)化為字符串,格式為yyyy-MM-dd HH:mm:ss
*/
private static String getCnDate(Date date) {
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
/**
* Excel 導(dǎo)出,POI實現(xiàn)
*
* @param fileName 文件名
* @param sheetName sheet頁名稱
* @param columnNames 表頭列表名
* @param sheetTitle sheet頁Title
* @param objects 目標(biāo)數(shù)據(jù)集
*/
public static File writeExcel(String directory, String fileName, String sheetName, List<String> columnNames,
String sheetTitle, List<List<Object>> objects, boolean append) throws ReportInternalException, IOException {
File tmpFile = assertFile(directory, fileName);
return exportExcel(tmpFile, sheetName, columnNames, sheetTitle, objects, append);
}
/**
* Excel 導(dǎo)出瓣戚,POI實現(xiàn)端圈,先寫入Excel標(biāo)題焦读,與writeExcelData配合使用
* 先使用writeExcelTitle再使用writeExcelData
*
* @param directory 目錄
* @param fileName 文件名
* @param sheetName sheetName
* @param columnNames 列名集合
* @param sheetTitle 表格標(biāo)題
* @param append 是否在現(xiàn)有的文件追加
* @return file
* @throws ReportInternalException
* @throws IOException
*/
public static File writeExcelTitle(String directory, String fileName, String sheetName, List<String> columnNames,
String sheetTitle, boolean append) throws ReportInternalException, IOException {
File tmpFile = assertFile(directory, fileName);
return exportExcelTitle(tmpFile, sheetName, columnNames, sheetTitle, append);
}
/**
* Excel 導(dǎo)出,POI實現(xiàn)舱权,寫入Excel數(shù)據(jù)行列矗晃,與writeExcelTitle配合使用
* 先使用writeExcelTitle再使用writeExcelData
*
* @param directory 目錄
* @param fileName 文件名
* @param sheetName sheetName
* @param objects 數(shù)據(jù)信息
* @return file
* @throws ReportInternalException
* @throws IOException
*/
public static File writeExcelData(String directory, String fileName, String sheetName, List<List<Object>> objects)
throws ReportInternalException, IOException {
File tmpFile = assertFile(directory, fileName);
return exportExcelData(tmpFile, sheetName, objects);
}
/**
* 導(dǎo)出字符串?dāng)?shù)據(jù)
*
* @param file 文件名
* @param columnNames 表頭
* @param sheetTitle sheet頁Title
* @param append 是否追加寫文件
* @return file
* @throws ReportInternalException
*/
private static File exportExcelTitle(File file, String sheetName, List<String> columnNames,
String sheetTitle, boolean append) throws ReportInternalException, IOException {
// 聲明一個工作薄
Workbook workBook;
if (file.exists() && append) {
workBook = new XSSFWorkbook(new FileInputStream(file));
} else {
workBook = new XSSFWorkbook();
}
Map<String, CellStyle> cellStyleMap = styleMap(workBook);
// 表頭樣式
CellStyle headStyle = cellStyleMap.get("head");
// 生成一個表格
Sheet sheet = workBook.getSheet(sheetName);
if (sheet == null) {
sheet = workBook.createSheet(sheetName);
}
//最新Excel列索引,從0開始
int lastRowIndex = sheet.getLastRowNum();
if (lastRowIndex > 0) {
lastRowIndex++;
}
// 設(shè)置表格默認(rèn)列寬度
sheet.setDefaultColumnWidth(DEFAULT_COLUMN_SIZE);
// 合并單元格
sheet.addMergedRegion(new CellRangeAddress(lastRowIndex, lastRowIndex, 0, columnNames.size() - 1));
// 產(chǎn)生表格標(biāo)題行
Row rowMerged = sheet.createRow(lastRowIndex);
lastRowIndex++;
Cell mergedCell = rowMerged.createCell(0);
mergedCell.setCellStyle(headStyle);
mergedCell.setCellValue(new XSSFRichTextString(sheetTitle));
// 產(chǎn)生表格表頭列標(biāo)題行
Row row = sheet.createRow(lastRowIndex);
for (int i = 0; i < columnNames.size(); i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(headStyle);
RichTextString text = new XSSFRichTextString(columnNames.get(i));
cell.setCellValue(text);
}
try {
OutputStream ops = new FileOutputStream(file);
workBook.write(ops);
ops.flush();
ops.close();
} catch (IOException e) {
throw new ReportInternalException(e);
}
return file;
}
/**
* 導(dǎo)出字符串?dāng)?shù)據(jù)
*
* @param file 文件名
* @param objects 目標(biāo)數(shù)據(jù)
* @return
* @throws ReportInternalException
*/
private static File exportExcelData(File file, String sheetName, List<List<Object>> objects) throws ReportInternalException, IOException {
// 聲明一個工作薄
Workbook workBook;
if (file.exists()) {
workBook = new XSSFWorkbook(new FileInputStream(file));
} else {
workBook = new XSSFWorkbook();
}
Map<String, CellStyle> cellStyleMap = styleMap(workBook);
// 正文樣式
CellStyle contentStyle = cellStyleMap.get("content");
//正文整數(shù)樣式
CellStyle contentIntegerStyle = cellStyleMap.get("integer");
//正文帶小數(shù)整數(shù)樣式
CellStyle contentDoubleStyle = cellStyleMap.get("double");
// 生成一個表格
Sheet sheet = workBook.getSheet(sheetName);
if (sheet == null) {
sheet = workBook.createSheet(sheetName);
}
//最新Excel列索引,從0開始
int lastRowIndex = sheet.getLastRowNum();
if (lastRowIndex > 0) {
lastRowIndex++;
}
// 設(shè)置表格默認(rèn)列寬度
sheet.setDefaultColumnWidth(DEFAULT_COLUMN_SIZE);
// 遍歷集合數(shù)據(jù),產(chǎn)生數(shù)據(jù)行,前兩行為標(biāo)題行與表頭行
for (List<Object> dataRow : objects) {
Row row = sheet.createRow(lastRowIndex);
lastRowIndex++;
for (int j = 0; j < dataRow.size(); j++) {
Cell contentCell = row.createCell(j);
Object dataObject = dataRow.get(j);
if (dataObject != null) {
if (dataObject instanceof Integer) {
contentCell.setCellStyle(contentIntegerStyle);
contentCell.setCellValue(Integer.parseInt(dataObject.toString()));
} else if (dataObject instanceof Double) {
contentCell.setCellStyle(contentDoubleStyle);
contentCell.setCellValue(Double.parseDouble(dataObject.toString()));
} else if (dataObject instanceof Long && dataObject.toString().length() == 13) {
contentCell.setCellStyle(contentStyle);
contentCell.setCellValue(getCnDate(new Date(Long.parseLong(dataObject.toString()))));
} else if (dataObject instanceof Date) {
contentCell.setCellStyle(contentStyle);
contentCell.setCellValue(getCnDate((Date) dataObject));
} else {
contentCell.setCellStyle(contentStyle);
contentCell.setCellValue(dataObject.toString());
}
} else {
contentCell.setCellStyle(contentStyle);
// 設(shè)置單元格內(nèi)容為字符型
contentCell.setCellValue("");
}
}
}
try {
OutputStream ops = new FileOutputStream(file);
workBook.write(ops);
ops.flush();
ops.close();
} catch (IOException e) {
throw new ReportInternalException(e);
}
return file;
}
/**
* 導(dǎo)出字符串?dāng)?shù)據(jù)
*
* @param file 文件名
* @param columnNames 表頭
* @param sheetTitle sheet頁Title
* @param objects 目標(biāo)數(shù)據(jù)
* @param append 是否追加寫文件
* @return
* @throws ReportInternalException
*/
private static File exportExcel(File file, String sheetName, List<String> columnNames,
String sheetTitle, List<List<Object>> objects, boolean append) throws ReportInternalException, IOException {
// 聲明一個工作薄
Workbook workBook;
if (file.exists() && append) {
// 聲明一個工作薄
workBook = new XSSFWorkbook(new FileInputStream(file));
} else {
workBook = new XSSFWorkbook();
}
Map<String, CellStyle> cellStyleMap = styleMap(workBook);
// 表頭樣式
CellStyle headStyle = cellStyleMap.get("head");
// 正文樣式
CellStyle contentStyle = cellStyleMap.get("content");
//正文整數(shù)樣式
CellStyle contentIntegerStyle = cellStyleMap.get("integer");
//正文帶小數(shù)整數(shù)樣式
CellStyle contentDoubleStyle = cellStyleMap.get("double");
// 生成一個表格
Sheet sheet = workBook.getSheet(sheetName);
if (sheet == null) {
sheet = workBook.createSheet(sheetName);
}
//最新Excel列索引,從0開始
int lastRowIndex = sheet.getLastRowNum();
if (lastRowIndex > 0) {
lastRowIndex++;
}
// 設(shè)置表格默認(rèn)列寬度
sheet.setDefaultColumnWidth(DEFAULT_COLUMN_SIZE);
// 合并單元格
sheet.addMergedRegion(new CellRangeAddress(lastRowIndex, lastRowIndex, 0, columnNames.size() - 1));
// 產(chǎn)生表格標(biāo)題行
Row rowMerged = sheet.createRow(lastRowIndex);
lastRowIndex++;
Cell mergedCell = rowMerged.createCell(0);
mergedCell.setCellStyle(headStyle);
mergedCell.setCellValue(new XSSFRichTextString(sheetTitle));
// 產(chǎn)生表格表頭列標(biāo)題行
Row row = sheet.createRow(lastRowIndex);
lastRowIndex++;
for (int i = 0; i < columnNames.size(); i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(headStyle);
RichTextString text = new XSSFRichTextString(columnNames.get(i));
cell.setCellValue(text);
}
// 遍歷集合數(shù)據(jù),產(chǎn)生數(shù)據(jù)行,前兩行為標(biāo)題行與表頭行
for (List<Object> dataRow : objects) {
row = sheet.createRow(lastRowIndex);
lastRowIndex++;
for (int j = 0; j < dataRow.size(); j++) {
Cell contentCell = row.createCell(j);
Object dataObject = dataRow.get(j);
if (dataObject != null) {
if (dataObject instanceof Integer) {
contentCell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
contentCell.setCellStyle(contentIntegerStyle);
contentCell.setCellValue(Integer.parseInt(dataObject.toString()));
} else if (dataObject instanceof Double) {
contentCell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
contentCell.setCellStyle(contentDoubleStyle);
contentCell.setCellValue(Double.parseDouble(dataObject.toString()));
} else if (dataObject instanceof Long && dataObject.toString().length() == 13) {
contentCell.setCellType(XSSFCell.CELL_TYPE_STRING);
contentCell.setCellStyle(contentStyle);
contentCell.setCellValue(getCnDate(new Date(Long.parseLong(dataObject.toString()))));
} else if (dataObject instanceof Date) {
contentCell.setCellType(XSSFCell.CELL_TYPE_STRING);
contentCell.setCellStyle(contentStyle);
contentCell.setCellValue(getCnDate((Date) dataObject));
} else {
contentCell.setCellType(XSSFCell.CELL_TYPE_STRING);
contentCell.setCellStyle(contentStyle);
contentCell.setCellValue(dataObject.toString());
}
} else {
contentCell.setCellStyle(contentStyle);
// 設(shè)置單元格內(nèi)容為字符型
contentCell.setCellValue("");
}
}
}
try {
OutputStream ops = new FileOutputStream(file);
workBook.write(ops);
ops.flush();
ops.close();
} catch (IOException e) {
throw new ReportInternalException(e);
}
return file;
}
/**
* 創(chuàng)建單元格表頭樣式
*
* @param workbook 工作薄
*/
private static CellStyle createCellHeadStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
// 設(shè)置邊框樣式
style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
style.setBorderRight(XSSFCellStyle.BORDER_THIN);
style.setBorderTop(XSSFCellStyle.BORDER_THIN);
//設(shè)置對齊樣式
style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
// 生成字體
Font font = workbook.createFont();
// 表頭樣式
style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
// 把字體應(yīng)用到當(dāng)前的樣式
style.setFont(font);
return style;
}
/**
* 創(chuàng)建單元格正文樣式
*
* @param workbook 工作薄
*/
private static CellStyle createCellContentStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
// 設(shè)置邊框樣式
style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
style.setBorderRight(XSSFCellStyle.BORDER_THIN);
style.setBorderTop(XSSFCellStyle.BORDER_THIN);
//設(shè)置對齊樣式
style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
// 生成字體
Font font = workbook.createFont();
// 正文樣式
style.setFillPattern(XSSFCellStyle.NO_FILL);
style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
font.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
// 把字體應(yīng)用到當(dāng)前的樣式
style.setFont(font);
return style;
}
/**
* 單元格樣式(Integer)列表
*/
private static CellStyle createCellContent4IntegerStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
// 設(shè)置邊框樣式
style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
style.setBorderRight(XSSFCellStyle.BORDER_THIN);
style.setBorderTop(XSSFCellStyle.BORDER_THIN);
//設(shè)置對齊樣式
style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
// 生成字體
Font font = workbook.createFont();
// 正文樣式
style.setFillPattern(XSSFCellStyle.NO_FILL);
style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
font.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
// 把字體應(yīng)用到當(dāng)前的樣式
style.setFont(font);
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0"));//數(shù)據(jù)格式只顯示整數(shù)
return style;
}
/**
* 單元格樣式(Double)列表
*/
private static CellStyle createCellContent4DoubleStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
// 設(shè)置邊框樣式
style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
style.setBorderRight(XSSFCellStyle.BORDER_THIN);
style.setBorderTop(XSSFCellStyle.BORDER_THIN);
//設(shè)置對齊樣式
style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
// 生成字體
Font font = workbook.createFont();
// 正文樣式
style.setFillPattern(XSSFCellStyle.NO_FILL);
style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
font.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
// 把字體應(yīng)用到當(dāng)前的樣式
style.setFont(font);
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00"));//保留兩位小數(shù)點
return style;
}
/**
* 單元格樣式列表
*/
private static Map<String, CellStyle> styleMap(Workbook workbook) {
Map<String, CellStyle> styleMap = new LinkedHashMap<>();
styleMap.put("head", createCellHeadStyle(workbook));
styleMap.put("content", createCellContentStyle(workbook));
styleMap.put("integer", createCellContent4IntegerStyle(workbook));
styleMap.put("double", createCellContent4DoubleStyle(workbook));
return styleMap;
}
}
使用例子
import java.io.IOException;
import java.sql.Date;
import java.util.LinkedList;
import java.util.List;
/**
* Excel2007Test
* Created by jianwei.zhou on 2016/11/9.
*/
public class Excel2007Test {
public static void main(String[] args) throws IOException {
String sheetName = "測試Excel格式";
String sheetTitle = "測試Excel格式";
List<String> columnNames = new LinkedList<>();
columnNames.add("日期-String");
columnNames.add("日期-Date");
columnNames.add("時間戳-Long");
columnNames.add("客戶編碼");
columnNames.add("整數(shù)");
columnNames.add("帶小數(shù)的正數(shù)");
//寫入標(biāo)題--第二種方式
Excel2007Utils.writeExcelTitle("E:\\temp", "a", sheetName, columnNames, sheetTitle, false);
List<List<Object>> objects = new LinkedList<>();
for (int i = 0; i < 1000; i++) {
List<Object> dataA = new LinkedList<>();
dataA.add("2016-09-05 17:27:25");
dataA.add(new Date(1451036631012L));
dataA.add(1451036631012L);
dataA.add("000628");
dataA.add(i);
dataA.add(1.323 + i);
objects.add(dataA);
}
try {
//寫入數(shù)據(jù)--第二種方式
Excel2007Utils.writeExcelData("E:\\temp", "a", sheetName, objects);
//直接寫入數(shù)據(jù)--第一種方式
Excel2007Utils.writeExcel("E:\\temp", "a", sheetName, columnNames, sheetTitle, objects, false);
} catch (Exception e) {
e.printStackTrace();
}
}
}