Directly on the code:
poi version is greater than 3.8
public class ExcelUtil {
//Declare a template workbook (write streaming data)
private Workbook writeDataWorkBook;
//Style list
private Map<String, CellStyle> cellStyleMap;
//The current number of data rows in Excel (The index number of the data to be written)
private int currentRowNum = 0;
//Data output stream
private OutputStream outputStream;
/**
* Release resources
*/
public void dispose() {
try {
if (writeDataWorkBook != null) {
writeDataWorkBook. write(outputStream);
}
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
if (cellStyleMap != null) {
cellStyleMap.clear();
}
cellStyleMap = null;
outputStream = null;
writeDataWorkBook = null;
} catch (IOException e) {
}
}
/**
* 导出字符串数据
*
* @param file 文件名
* @param columnNames 表头
* @param sheetTitle sheet页Title
*/
public void exportExcelTitle(HttpServletResponse response, String sheetName, List<String> columnNames,
String sheetTitle, List<List<Object>> objects) {
//Create Excel
XSSFWorkbook in xlsx format wb = new XSSFWorkbook();
/**
* The table to which SXSSFWorkbook is written, which can be written massively
* Parameters:
* @wb2007 Version Excel
* @100 batch write number
*/
SXSSFWorkbook tplWorkBook = new SXSSFWorkbook(wb, 100);
Map<String, CellStyle> cellStyleMap = styleMap(tplWorkBook);
// header style
CellStyle headStyle = cellStyleMap.get("head ");
// Generate a sheet
Sheet sheet = tplWorkBook.getSheet(sheetName);
if (sheet == null) {
sheet = tplWorkBook.createSheet(sheetName);
}
// merge cells
sheet.addMergedRegion(new CellRangeAddress(currentRowNum, currentRowNum, 0, columnNames.size() - 1));
// generate table header row
Row rowMerged = sheet.createRow (currentRowNum);
Cell mergedCell = rowMerged.createCell(0);
mergedCell.setCellStyle(headStyle);
mergedCell.setCellValue(new XSSFRichTextString(sheetTitle));
//Increase the number of rows after writing a row of data
currentRowNum = currentRowNum + 1;
// Generate table header column header row
Row row = sheet.createRow(currentRowNum);
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);
} //Increase the number of rows currentRowNum
after writing a row of data
= currentRowNum + 1;
//content style
CellStyle contentStyle = cellStyleMap.get("content");
//body integer style
CellStyle contentIntegerStyle = cellStyleMap.get("integer");
//body style with decimal integers
CellStyle contentDoubleStyle = cellStyleMap. get("double");
for (List<Object> dataRow : objects) {
Row row1 = sheet.createRow(currentRowNum);
for (int j = 0; j < dataRow.size(); j++) {
Cell contentCell = row1.createCell(j);
Object dataObject = dataRow.get(j);
contentCell.setCellStyle(contentStyle);
String str = dataObject.toString();
if(str.contains("-") && str.contains(":") && str.contains(".0")){
str.trim();
str = str.substring(0, str.lastIndexOf(" "));
contentCell.setCellStyle(contentStyle);
contentCell.setCellValue(str);
}else if(this.isNum(str)){
if(str.contains(".")){
contentCell.setCellStyle(contentDoubleStyle);
contentCell.setCellValue(Double.parseDouble(str));
}else{
contentCell.setCellStyle(contentIntegerStyle);
contentCell.setCellValue(Integer.parseInt(str));
}
}else{
contentCell.setCellStyle(contentStyle);
contentCell.setCellValue(str);
}
}
//写入成功一行数据递增行数
currentRowNum = currentRowNum + 1;
}
for(int i = 0 ; i<columnNames.size() ; i ++){
sheet.autoSizeColumn((short)i); //调整宽度
}
try {
this.setResponseHeader(response, sheetName);
OutputStream ops = response.getOutputStream();
tplWorkBook.write(ops);
ops.flush();
ops.close();
} catch (IOException e) {
}
}
public void exportExcelCompare(HttpServletResponse response, String sheetName, List<String> columnNames,
String sheetTitle, List<List<Object>> objects,int length) {
Workbook tplWorkBook = new XSSFWorkbook();
Map<String, CellStyle> cellStyleMap = styleMap(tplWorkBook);
// 表头样式
CellStyle headStyle = cellStyleMap.get("head");
CellStyle contentStyle = cellStyleMap.get("content");
// generate a sheet
Sheet sheet = tplWorkBook.getSheet(sheetName);
if (sheet == null) {
sheet = tplWorkBook .createSheet(sheetName);
}
// Merge cells
sheet.addMergedRegion(new CellRangeAddress(currentRowNum, currentRowNum, 0, columnNames.size() - 1));
// Generate table header row
Row rowMerged = sheet.createRow(currentRowNum) ;
Cell mergedCell = rowMerged.createCell(0);
mergedCell.setCellStyle(headStyle);
mergedCell.setCellValue(new XSSFRichTextString(sheetTitle));
//Increase the number of rows after writing a row of data
currentRowNum = currentRowNum + 1;
// Generate a table header column header row
Row row = sheet.createRow(currentRowNum);
sheet.addMergedRegion(new CellRangeAddress(currentRowNum, currentRowNum, 0,length));
sheet.addMergedRegion(new CellRangeAddress(currentRowNum, currentRowNum, length+1,length*2+1));
Cell headerCell = row.createCell(0);
headerCell.setCellStyle(contentStyle);
headerCell.setCellValue("CAA");
Cell headerCells = row.createCell(8);
headerCells.setCellStyle(contentStyle);
headerCells.setCellValue("null Management Bureau");
//Increase the number of rows when writing a row of data successfully
currentRowNum = currentRowNum + 1;
//Text integer style
CellStyle contentIntegerStyle = cellStyleMap.get("integer");
//Text with decimal integer style
CellStyle contentDoubleStyle = cellStyleMap. get(" double");
for (List<Object> dataRow : objects) {
Row row1 = sheet.createRow(currentRowNum);
for (int j = 0; j < dataRow.size(); j++) {
Cell contentCell = row1.createCell(j);
Object dataObject = dataRow.get(j);
contentCell.setCellStyle(contentStyle);
String str = dataObject.toString();
if(str.contains("-") && str.contains(":") && str.contains(".0")){
str.trim();
str = str.substring(0, str.lastIndexOf(" "));
contentCell.setCellStyle(contentStyle);
contentCell.setCellValue(str);
}else if(this.isNum(str)){
if(str.contains(".")){
contentCell.setCellStyle(contentDoubleStyle);
contentCell.setCellValue(Double.parseDouble(str));
}else{
contentCell.setCellStyle(contentIntegerStyle);
contentCell.setCellValue(Integer.parseInt(str));
}
}else{
contentCell.setCellStyle(contentStyle);
contentCell.setCellValue(str);
}
}
//写入成功一行数据递增行数
currentRowNum = currentRowNum + 1;
}
for(int i = 0 ; i<columnNames.size() ; i ++){
sheet.autoSizeColumn((short)i); //调整宽度
}
try {
this.setResponseHeader(response, sheetName);
OutputStream ops = response.getOutputStream();
tplWorkBook.write(ops);
ops.flush();
ops.close();
} catch (IOException e) {
}
}
/**
* 设置响应头
* @param response
* @param fileName
*/
public void setResponseHeader(HttpServletResponse response, String fileName) {
try {
fileName = new String(fileName.getBytes(),"ISO8859-1");
response.setContentType("application/octet-stream;charset=ISO8859-1");
response.setHeader("Content-Disposition", "attachment;filename="+ fileName+".xlsx");
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Determine if it is numeric data
*/
public boolean isNum(String str) {
try {
new BigDecimal(str);
if(str.contains("E")){
return false;
}
return true;
} catch (Exception e) {
return false;
}
}
/**
* List of cell styles (Integer)
*/
private CellStyle createCellContent4IntegerStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
// Set border style
style.setBorderBottom(XSSFCellStyle .BORDER_THIN);
style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
style.setBorderRight(XSSFCellStyle.BORDER_THIN);
style.setBorderTop(XSSFCellStyle.BORDER_THIN);
//Set the alignment style
style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
//Generate font
Font font = workbook. createFont();
// body style
style.setFillPattern(XSSFCellStyle.NO_FILL);
style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
font.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
// apply font to current style
style.setFont(font) ;
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0"));//The data format only displays integers
return style;
}
/**
* List of cell styles (Double)
*/
private CellStyle createCellContent4DoubleStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
// Set border style
style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
style.setBorderLeft(XSSFCellStyle .BORDER_THIN);
style.setBorderRight(XSSFCellStyle.BORDER_THIN);
style.setBorderTop(XSSFCellStyle.BORDER_THIN);
//Set the alignment style
style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
//Generate font
Font font = workbook.createFont();
/ / Body style
style.setFillPattern(XSSFCellStyle.NO_FILL);
style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
font.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
// apply the font to the current style
style.setFont(font);
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00") );//Retain two decimal points
return style;
}
/**
* Create cell header style
*
* @param workbook workbook
*/
private CellStyle createCellHeadStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
// Set the border style
style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
style.setBorderRight(XSSFCellStyle.BORDER_THIN);
style.setBorderTop(XSSFCellStyle.BORDER_THIN);
//Set the alignment style
style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
//Generate font
Font font = workbook.createFont();
//Header style
style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
// Apply the font to the current style
style. setFont(font);
return style;
}
/**
* Create cell body style
*
* @param workbook workbook
*/
private CellStyle createCellContentStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
// Set border style
style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
style. setBorderRight(XSSFCellStyle.BORDER_THIN);
style.setBorderTop(XSSFCellStyle.BORDER_THIN);
//Set alignment style
style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
//Generate font
Font font = workbook.createFont();
//Text style
style.setFillPattern (XSSFCellStyle.NO_FILL);
style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
font.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
// apply font to current style
style.setFont(font);
return style;
}
/**
* cell style list
*/
private Map <String, CellStyle> styleMap(Workbook workbook) {
Map<String, CellStyle> styleMap = new LinkedHashMap<String, CellStyle>();
styleMap.put("head", createCellHeadStyle(workbook));
styleMap.put("content" , createCellContentStyle(workbook));
styleMap.put("integer", createCellContent4IntegerStyle(workbook));
styleMap.put("double", createCellContent4DoubleStyle(workbook));
return styleMap;
}
}
Batch export to Excel (.xlsx format)
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=326206760&siteId=291194637
Recommended
Ranking