HSSFWorkbook生成多个sheet页

假如想象 提交于 2020-01-25 07:47:32

public static void exportExcel(HSSFWorkbook workbook, int sheetNum, String sheetTitle, String[] headers,
List<List> result, OutputStream out) throws Exception {
workbook.setSheetName(sheetNum,sheetTitlelist);//设置sheet页标题
// 创建一个sheet页
HSSFSheet sheet = workbook.createSheet();
// 设置表格默认列宽度为20个字节
sheet.setDefaultColumnWidth((short) 20);
// 表格样式
HSSFCellStyle style = workbook.createCellStyle();
// 设置这些样式
style.setFillForegroundColor(HSSFColor.PALE_BLUE.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);// 当单元格内容显示不下时自动换行

	// 产生表格抬头
	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);
				cell.setCellValue(str.toString());
				cellIndex++;
			}
			index++;
		}
	}
}

public static void main(String[] args) {
	try {
	OutputStream out = new FileOutputStream("E:\\test.xls");
	List<List<String>> data = new ArrayList<List<String>>();
	for (int i = 1; i < 5; i++) {
	List rowData = new ArrayList();
	rowData.add(String.valueOf(i));
	rowData.add("第二列数据");
	data.add(rowData);
	}
	String[] headers = { "ID", "用户名" };
	HSSFWorkbook workbook = new HSSFWorkbook();
	exportExcel(workbook, 0, "上海", headers, data, out);
	exportExcel(workbook, 1, "深圳", headers, data, out);
	workbook.write(out);
	out.close();
	} catch (Exception e) {
	e.printStackTrace();
	}
	}

注:sheet名称不能多于31个(包含英文、汉字、| 、()等,但是不能包含: 、/、?、*、[]等 ),程序中使用poi工具来生成的时候,传进去大于31个长度的字符串时,会被自动截取,便会导致两个名字变为一样的,出现sheet同名异常

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!