工具类
package com.longrise.SWMS.Util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelUtils {
private static final int DEFAULT_COLUMN_SIZE = 20;
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;
}
private static String getCnDate(Date date) {
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
public static File writeExcel(String directory, String fileName, String sheetName, List < String > columnNames,List<String> titleInfo,
String sheetTitle, List < List < Object >> objects, boolean append) throws IOException {
File tmpFile = assertFile(directory, fileName);
return exportExcel(tmpFile, sheetName, columnNames,titleInfo, sheetTitle, objects, append);
}
public static File writeExcelTitle(String directory, String fileName, String sheetName, List < String > columnNames,
String sheetTitle, boolean append) throws IOException {
File tmpFile = assertFile(directory, fileName);
return exportExcelTitle(tmpFile, sheetName, columnNames, sheetTitle, append);
}
public static File writeExcelData(String directory, String fileName, String sheetName, List < List < Object >>
objects)
throws IOException {
File tmpFile = assertFile(directory, fileName);
return exportExcelData(tmpFile, sheetName, objects);
}
private static File exportExcelTitle(File file, String sheetName, List < String > columnNames,
String sheetTitle, boolean append) throws 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);
}
int lastRowIndex = sheet.getLastRowNum();
if (lastRowIndex > 0) {
lastRowIndex++;
}
sheet.addMergedRegion(new CellRangeAddress(lastRowIndex, lastRowIndex, 0, columnNames.size() - 1));
Row rowMerged = sheet.createRow(lastRowIndex);
lastRowIndex++;
Cell mergedCell = rowMerged.createCell(0);
mergedCell.setCellStyle(headStyle);
mergedCell.setCellValue(new XSSFRichTextString(sheetTitle));
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) {
System.err.println(e);
}
return file;
}
private static File exportExcelData(File file, String sheetName, List < List < Object >> objects) throws 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");
CellStyle contentIntegerStyle = cellStyleMap.get("integer");
CellStyle contentDoubleStyle = cellStyleMap.get("double");
Sheet sheet = workBook.getSheet(sheetName);
if (sheet == null) {
sheet = workBook.createSheet(sheetName);
}
int lastRowIndex = sheet.getLastRowNum();
if (lastRowIndex > 0) {
lastRowIndex++;
}
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) {
sheet.autoSizeColumn(j, true);
sheet.setColumnWidth(j,dataObject.toString().length()*2*256);
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);
contentCell.setCellValue("");
}
}
}
try {
OutputStream ops = new FileOutputStream(file);
workBook.write(ops);
ops.flush();
ops.close();
} catch (IOException e) {
System.err.println(e);
}
return file;
}
private static File exportExcel(File file, String sheetName, List < String > columnNames,List <String > titleInfo,
String sheetTitle, List < List < Object >> objects, boolean append) throws 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");
CellStyle titleStyle = cellStyleMap.get("title");
CellStyle contentIntegerStyle = cellStyleMap.get("integer");
CellStyle contentDoubleStyle = cellStyleMap.get("double");
Sheet sheet = workBook.getSheet(sheetName);
if (sheet == null) {
sheet = workBook.createSheet(sheetName);
}
int lastRowIndex = sheet.getLastRowNum();
if (lastRowIndex > 0) {
lastRowIndex++;
}
sheet.setDefaultColumnWidth(DEFAULT_COLUMN_SIZE);
sheet.addMergedRegion(new CellRangeAddress(lastRowIndex, lastRowIndex, 0, columnNames.size() - 1));
Row rowMerged = sheet.createRow(lastRowIndex);
lastRowIndex++;
Cell mergedCell = rowMerged.createCell(0);
mergedCell.setCellStyle(headStyle);
mergedCell.setCellValue(new XSSFRichTextString(sheetTitle));
sheet.addMergedRegion(new CellRangeAddress(lastRowIndex, lastRowIndex, 1,2));
sheet.addMergedRegion(new CellRangeAddress(lastRowIndex, lastRowIndex, 4,5));
sheet.addMergedRegion(new CellRangeAddress(lastRowIndex, lastRowIndex, 6,columnNames.size() - 1));
Row rowInfo = sheet.createRow(lastRowIndex);
lastRowIndex++;
for (int i = 0; i < titleInfo.size(); i++) {
Cell cell = rowInfo.createCell(i);
cell.setCellStyle(contentStyle);
RichTextString text = new XSSFRichTextString(titleInfo.get(i));
cell.setCellValue(text);
}
Row row = sheet.createRow(lastRowIndex);
lastRowIndex++;
for (int i = 0; i < columnNames.size(); i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(titleStyle);
RichTextString text = new XSSFRichTextString(columnNames.get(i));
cell.setCellValue(text);
}
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);
contentCell.setCellValue("");
}
}
}
try {
OutputStream ops = new FileOutputStream(file);
workBook.write(ops);
ops.flush();
ops.close();
} catch (IOException e) {
System.err.println(e);
}
return file;
}
private static CellStyle createCellHeadStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
style.setBorderRight(XSSFCellStyle.BORDER_THIN);
style.setBorderTop(XSSFCellStyle.BORDER_THIN);
style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
Font font = workbook.createFont();
style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
font.setFontHeightInPoints((short) 16);
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
style.setFont(font);
return style;
}
private static CellStyle createCellTitleStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
style.setBorderRight(XSSFCellStyle.BORDER_THIN);
style.setBorderTop(XSSFCellStyle.BORDER_THIN);
style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
Font font = workbook.createFont();
style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
style.setFont(font);
return style;
}
private static CellStyle createCellContentStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
style.setBorderRight(XSSFCellStyle.BORDER_THIN);
style.setBorderTop(XSSFCellStyle.BORDER_THIN);
style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
style.setWrapText(true);
Font font = workbook.createFont();
style.setFillPattern(XSSFCellStyle.NO_FILL);
style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
font.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
style.setFont(font);
return style;
}
private static CellStyle createCellContent4IntegerStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
style.setBorderRight(XSSFCellStyle.BORDER_THIN);
style.setBorderTop(XSSFCellStyle.BORDER_THIN);
style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
Font font = workbook.createFont();
style.setFillPattern(XSSFCellStyle.NO_FILL);
style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
font.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
style.setFont(font);
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0"));
return style;
}
private static CellStyle createCellContent4DoubleStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
style.setBorderRight(XSSFCellStyle.BORDER_THIN);
style.setBorderTop(XSSFCellStyle.BORDER_THIN);
style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
Font font = workbook.createFont();
style.setFillPattern(XSSFCellStyle.NO_FILL);
style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
font.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
style.setFont(font);
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00"));
return style;
}
private static Map < String, CellStyle > styleMap(Workbook workbook) {
Map < String, CellStyle > styleMap = new LinkedHashMap <String, CellStyle > ();
styleMap.put("head", createCellHeadStyle(workbook));
styleMap.put("title", createCellTitleStyle(workbook));
styleMap.put("content", createCellContentStyle(workbook));
styleMap.put("integer", createCellContent4IntegerStyle(workbook));
styleMap.put("double", createCellContent4DoubleStyle(workbook));
return styleMap;
}
}
测试类
package client;
import java.io.IOException;
import java.sql.Date;
import java.util.LinkedList;
import java.util.List;
import tools.ExcelUtils;
public class ExploreTest {
public static void main(String[] args) throws IOException {
String sheetName = "sheet名字";
String sheetTitle = "标头";
List < String > columnNames = new LinkedList < > ();
columnNames.add("测试标头长度自适应测试标头长度自适应测试标头长度自适应");
columnNames.add("单元格2");
columnNames.add("单元格3");
columnNames.add("单元格4");
columnNames.add("单元格5");
columnNames.add("单元格6");
ExcelUtils.writeExcelTitle("D:\\tset", "biaoming1", sheetName, columnNames, sheetTitle, false);
List < List < Object >> objects = new LinkedList < > ();
for (int i = 0; i < 5; i++) {
List < Object > dataA = new LinkedList < > ();
dataA.add("哈哈");
dataA.add(new Date(1451036631012L));
dataA.add(1451036631012L);
dataA.add("测试标头长度自适应测试标头长度自适应测试标头长度自适应");
dataA.add(i);
dataA.add(1.323 + i);
objects.add(dataA);
}
try {
ExcelUtils.writeExcelData("D:\\tset", "biaoming1", sheetName, objects);
ExcelUtils.writeExcel("D:\\tset", "biaoming2", sheetName, columnNames, sheetTitle, objects, false);
System.out.println("数据写入成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
}