1.工具类
public void exportExcel(HSSFWorkbook workbook, int sheetNum,
String sheetTitle, String[] headers, List<List<String>> result,
OutputStream out) throws Exception {
HSSFSheet sheet = workbook.createSheet();
workbook.setSheetName(sheetNum, sheetTitle);
sheet.setDefaultColumnWidth((short) 20);
HSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.PALE_BLUE.index);
style.setFillBackgroundColor(HSSFColor.WHITE.index);
style.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index);
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.BLACK.index);
font.setFontHeightInPoints((short) 12);
style.setFont(font);
style.setWrapText(true);
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell((short) i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text.toString());
}
if (result != null) {
int index = 1;
for (List<String> m : result) {
row = sheet.createRow(index);
int cellIndex = 0;
for (String str : m) {
HSSFCell cell = row.createCell((short) cellIndex);
if(null != str){
cell.setCellValue(str.toString());
}else{
cell.setCellValue("");
}
cellIndex++;
}
index++;
}
}
}
2.具体应用(根据需求灵活使用)
public static void main(String[] args) {
try {
File f= new File("d:" + File.separator + "test.xls") ;
OutputStream out = new FileOutputStream(f);
List<List<String>> data1 = new ArrayList<List<String>>();
List<List<String>> data2 = new ArrayList<List<String>>();
List<List<String>> data3 = new ArrayList<List<String>>();
for (int i = 1; i < 5; i++) {
List rowData = new ArrayList();
rowData.add(String.valueOf(i));
rowData.add("上海东霖柏鸿");
data1.add(rowData);
}
for (int i = 1; i < 5; i++) {
List rowData = new ArrayList();
rowData.add(String.valueOf(i));
rowData.add("深圳东霖柏鸿");
data2.add(rowData);
}
for (int i = 1; i < 5; i++) {
List rowData = new ArrayList();
rowData.add(String.valueOf(i));
rowData.add("广州东霖柏鸿");
data3.add(rowData);
}
String[] headers1 = { "ID1", "用户名1" };
String[] headers2 = { "ID2", "用户名2" };
String[] headers3 = { "ID3", "用户名3" };
HSSFWorkbook workbook = new HSSFWorkbook();
exportExcel(workbook, 0, "上海", headers1, data1, out);
exportExcel(workbook, 1, "深圳", headers2, data2, out);
exportExcel(workbook, 2, "广州", headers3, data3, out);
workbook.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}