环境:
1、下载JExcelApi解压找到jxl.jar包;
2、创建Java项目并引入jxl.jar包。
JExcelApi特性:
1、支持字体、日期和数字格式化;
2、支持单元格的颜色和背景设置;
3、可以编辑现有的文件。
导出数据到Excel中:
1、文件输出路径
File tempFile=new File("E:/output.xls");
2、声明一些临时变量用于写入Excel
//一些临时变量,用于写入Excel
Label lb=null;
jxl.write.Number number=null;
jxl.write.DateTime datetime=null;
3、预定义一些字体和颜色
// 预定义一些字体和格式
WritableFont headerFont = new WritableFont(WritableFont.ARIAL, 12,
WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
jxl.format.Colour.BLUE);
WritableCellFormat headerFormat = new WritableCellFormat(headerFont);
WritableFont titleFont = new WritableFont(WritableFont.ARIAL, 10,
WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,
jxl.format.Colour.RED);
WritableCellFormat titleFormat = new WritableCellFormat(titleFont);
WritableFont detFont = new WritableFont(WritableFont.ARIAL, 10,
WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,
jxl.format.Colour.BLACK);
WritableCellFormat detFormat = new WritableCellFormat(detFont);
4、预定义Number格式
// 用于Number格式
NumberFormat nf = new NumberFormat("0.00000");
WritableCellFormat priceFormat = new WritableCellFormat(detFont, nf);
DateFormat df = new DateFormat("yyyy-MM-dd");
WritableCellFormat dateFormat = new WritableCellFormat(detFont, df);
5、利用创建好的预定义格式,创建单元格并加入到sheet中
// 接下来,即使用上面的内容和格式创建一些单元格,在加到sheet中
public void ExcelInsert() throws RowsExceededException, WriteException {
try {
WritableWorkbook workbook = Workbook.createWorkbook(tempFile);
WritableSheet sheet = workbook.createSheet("myExcel", 0);
lb = new Label(0, 0, "用于测试的Excel文件", headerFormat);
sheet.addCell(lb);
// add Title
int column = 0;
lb = new Label(column++, 2, "标题", titleFormat);
sheet.addCell(lb);
lb = new Label(column++, 2, "日期", titleFormat);
sheet.addCell(lb);
lb = new Label(column++, 2, "货币", titleFormat);
sheet.addCell(lb);
lb = new Label(column++, 2, "价格", titleFormat);
sheet.addCell(lb);
// add Detail
int i = 0;
column = 0;
lb = new Label(column++, i + 3, "标题" + i, detFormat);
sheet.addCell(lb);
datetime = new DateTime(column++, i + 3, new java.util.Date(),
detFormat);
sheet.addCell(datetime);
lb = new Label(column++, i + 3, "CNY", detFormat);
sheet.addCell(lb);
number = new jxl.write.Number(column++, i + 3, 5.678, priceFormat);
sheet.addCell(number);
i++;
column = 0;
lb = new Label(column++, i + 3, "标题" + i, detFormat);
sheet.addCell(lb);
datetime = new DateTime(column++, i + 3, new java.util.Date(),
detFormat);
sheet.addCell(datetime);
lb = new Label(column++, i + 3, "SGD", detFormat);
sheet.addCell(lb);
number = new jxl.write.Number(column++, i + 3, 98832, priceFormat);
sheet.addCell(number);
// 设置类的宽度
column = 0;
sheet.setColumnView(column++, 20);
sheet.setColumnView(column++, 20);
sheet.setColumnView(column++, 10);
sheet.setColumnView(column++, 20);
workbook.write();
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
官网JExcelApi帮助文档: