创建excel

excel的导入导出是程序开发过程中非常常见的问题,常用的解析excel工具有poi或者jxl,下面看一下用jxl如何创建一个新的excel表格文件。

private LinkedHashMap<String, Map<String, String>> tableHeader;//表头信息
private String tableName;
private String tableHeaderCN; // 中文表头
private List<?> exportData;
@SuppressWarnings({ "rawtypes", "deprecation" })
public void createExcel() throws Throwable {
	File path = new File("exportTmp");
	if (!path.exists()) {
		path.mkdir();
	}
	File file = new File("exportTmp", fileName + ".xls");
	WritableWorkbook book = Workbook.createWorkbook(file);
	WritableSheet sheet = book.createSheet("sheet1", 0);

	// 设置格式
	jxl.write.WritableFont font1 = new jxl.write.WritableFont(
			jxl.write.WritableFont.TIMES, 16, jxl.write.WritableFont.BOLD);
	jxl.write.WritableFont font3 = new jxl.write.WritableFont(
			jxl.write.WritableFont.TIMES, 10, jxl.write.WritableFont.BOLD);

	jxl.write.WritableCellFormat CBwcfF1 = new jxl.write.WritableCellFormat(
			font1);
	jxl.write.WritableCellFormat CBwcfF2 = new jxl.write.WritableCellFormat(
			font3);
	jxl.write.WritableCellFormat CBwcfF3 = new jxl.write.WritableCellFormat();

	CBwcfF1.setAlignment(jxl.write.Alignment.CENTRE);
	CBwcfF2.setAlignment(jxl.write.Alignment.CENTRE);
	CBwcfF2.setBorder(Border.ALL, jxl.format.BorderLineStyle.THIN,
			Colour.BLACK);
	CBwcfF3.setBorder(Border.ALL, jxl.format.BorderLineStyle.THIN,
			Colour.BLACK);

	// 填充内容
	Label label = new Label(0, 0, tableName, CBwcfF1);
	Set<String> headers = tableHeader.keySet();
	String[] headersCN = tableHeaderCN.split(",");
	int columnCount = headers.size();
	sheet.addCell(label);
	sheet.mergeCells(0, 0, columnCount - 1, 0);
	for (int i = 0; i < columnCount; i++) {
		Label headLabel = new Label(i, 1, headersCN[i], CBwcfF2);
		sheet.addCell(headLabel);
	}

	int recordCount = exportData.size();
	List list = new ArrayList();
	list = getDataValues();

	for (int lineCount = 1; lineCount <= recordCount; lineCount++) {
		for (int j = 0; j < columnCount; j++) {
			Label valueLabel = new Label(j, lineCount + 1,
					(String) list.get((lineCount - 1) * columnCount + j),
					CBwcfF3);
			sheet.addCell(valueLabel);
		}
	}
	book.write();
	book.close();
}
 搞定!是不是很简单、实用。

你可能感兴趣的:(创建excel)