HSSFWorkbook生成多个sheet页

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同名异常

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值