JAVA中操作excel有两种比较主流的工具包:JXL和POI。JXL只能操作Excel 95,97,2000也即以.xls为后缀的excel。而poi支持office的所有版本,即可操作后缀为.xls和.xlsx两种格式的excel。
POI介绍:
Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office格式档案读和写的功能。POI为“Poor Obfuscation Implementation”的首字母缩写,意为“简洁版的模糊实现”。
POI可以操作的文档格式有excel,word,powerpoint等,在此介绍POI操作excel的步骤,关于POI操作其他文档的步骤,大家可以参考其他资料。
首先需要去apache poi的官网上下载poi开发包。http://poi.apache.org
一:导出excel表:
1、首先准备一些poi的jar包
2.下面粘个自己写的实例
@RequestMapping("/getDetailExcel")
public void getALlDetail(HttpServletRequest req,HttpServletResponse resp){
List<DetailRecord> resultList = recordService.getDetail(); //待导出excel的数据列表
// 创建Excel文档(声明一个工作簿)
HSSFWorkbook hwb = new HSSFWorkbook();
int CountColumnNum =6; //xls.size(); //定义excel表的总列数
// sheet 对应一个工作页,并加以命名
HSSFSheet sheet = hwb.createSheet("历史查询统计表");
//生成一个样式(可有可无)
HSSFCellStyle style = wb.createCellStyle();
//样式字体居中
style.setAlignment(HSSFCellStyle.ALIGN_CENTER)
//创建第一行(也可以称为表头)
HSSFRowfirstrow= sheet.createRow(0);
//给表头第一行一次创建单元格
HSSFCell[] firstcell = new HSSFCell[CountColumnNum];
//下面是给该表头每列的标识(名字)
String[] names = new String[CountColumnNum];
names[0] = "序号";
names[1] = "企业名称";
names[2] = "纳税人识别号";
names[3] = "查询时间";
names[4] = "报告编号";
names[5] = "历史报告";
for (int j = 0; j < CountColumnNum; j++) {
firstcell[j] = firstrow.createCell(j);
firstcell[j].setCellValue(new HSSFRichTextString(names[j]));
}
//对待导出的数据进行遍历并向表里添加数据
for (int i = 0; i <resultList.size(); i++) {
DetailRecord record = new DetailRecord();
record = resultList.get(i);
// 创建一行
HSSFRow row = sheet.createRow(i+1); //其中i+1是从表头下面一行开始添加数据
//开始在每一行开始填充数据
for(int col=0;i<CountColumnNum;col++){
HSSFCell id = row.createCell(0);
id.setCellValue(record.getId());
HSSFCell name = row.createCell(1);
name.setCellValue(record.getQymc());
HSSFCell yxsmc = row.createCell(2);
yxsmc.setCellValue(record.getJgdm());
HSSFCell kcm = row.createCell(3);
kcm.setCellValue(record.getSeltime());
HSSFCell sd = row.createCell(4);
sd.setCellValue(record.getBgbh());
HSSFCell address = row.createCell(5);
address.setCellValue(record.getAddress());
} sheet.autoSizeColumn((short)0); //调整第一列宽度
sheet.setColumnWidth(1, qymcSize*2*200); //对于中文字段,要进行特殊调整
// sheet.autoSizeColumn((short)1); //调整第二列宽度
sheet.autoSizeColumn((short)2); //调整第三列宽度
sheet.autoSizeColumn((short)3); //调整第四列宽度
sheet.autoSizeColumn((short)4); //调整第四列宽度
// 创建文件输出流,准备输出电子表格(以下载的形式,如果想要下载到本地的盘,则在创建文件时将路径改变即可)
try{
String filename = "历史查询明细表.xls"; //设置下载时客户端Excel的名称
filename = ExcelUtil.encodeFilename(filename, req);
//设置响应头,浏览器就知道以什么文件格式进行下载
resp.setContentType("application/vnd.ms-excel");
resp.setHeader("Content-disposition", "attachment;filename=" + filename);
OutputStream ouputStream = resp.getOutputStream();
hwb.write(ouputStream);
ouputStream.close();
System.out.println("数据库导出成功");
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 生成委托单--导出失败企业列表(包括原因)
* @param failEnterpriseList
* @param qyxxErrorList
* @return
*/
public Workbook exportFailEnterpriseList(Map<String,Object> allEnterpriseMap,String entrustmentformNumber,String reportId,String reportTypeContainsVersion,String entrustmentDate) {
List<Map<String,Object>> failEnterpriseList = (List<Map<String,Object>>) allEnterpriseMap.get("failEnterpriseList");
List<Map<String,Object>> qyxxErrorList = (List<Map<String,Object>>) allEnterpriseMap.get("qyxxErrorList");
List<Map<String,Object>> doubleReasonList = (List<Map<String,Object>>) allEnterpriseMap.get("doubleReasonList");
String failEnterpriseReason = null;
String qyxxErrorResion = "企业主体信息不匹配";
if(StringUtils.isNotBlank(reportId)){
if(reportId.equals(ReportEnum.SWBG.getKey())){
failEnterpriseReason = "非联盟成员企业";
}else if(reportId.equals(ReportEnum.SSLXBG10.getKey())){
failEnterpriseReason = "企业未对机构授权";
}
}
//HSSFWorkbook可以操作2003以前版本的excel XSSFWorkbook可以操作2007以上的版本
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet();
// ********************表头样式*****************************
XSSFFont headFont = workbook.createFont();
headFont.setFontName("宋体");//设置字体名称
// font.setFontHeightInPoints((short)28);//设置字号
headFont.setFontHeight(20);
headFont.setItalic(false);//设置是否为斜体
headFont.setBold(true);//设置是否加粗
headFont.setColor(IndexedColors.BLACK.index);//设置字体颜色
XSSFCellStyle headCellStyle = workbook.createCellStyle();
headCellStyle.setFont(headFont);
// 竖向居中
headCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 横向居中
headCellStyle.setAlignment(HorizontalAlignment.CENTER);
// 边框
headCellStyle.setBorderBottom(BorderStyle.THIN);
headCellStyle.setBorderLeft(BorderStyle.THIN);
headCellStyle.setBorderRight(BorderStyle.THIN);
headCellStyle.setBorderTop(BorderStyle.THIN);
// ************************内容字体样式***********************
XSSFFont contFont = workbook.createFont();
contFont.setBold(false);// 加粗
contFont.setFontName("宋体");
contFont.setColor(IndexedColors.BLACK.index);//设置字体颜色
contFont.setItalic(false);//设置是否为斜体
contFont.setFontHeight(15);
// 内容样式
XSSFCellStyle contentStyle = workbook.createCellStyle();
// 设置字体css
contentStyle.setFont(contFont);
// 竖向居中
contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 横向居中
contentStyle.setAlignment(HorizontalAlignment.CENTER);
// 边框
contentStyle.setBorderBottom(BorderStyle.THIN);
contentStyle.setBorderLeft(BorderStyle.THIN);
contentStyle.setBorderRight(BorderStyle.THIN);
contentStyle.setBorderTop(BorderStyle.THIN);
XSSFRow row1 = sheet.createRow(0);
XSSFCell row1Cell0 = row1.createCell(0);
row1Cell0.setCellValue("失败企业列表");
row1Cell0.setCellStyle(headCellStyle);
// 为了保证合并的单元格能有效追加外框、被合并的单元格、内容要设置为空
XSSFCell row1Cell1 = row1.createCell(1);
row1Cell1.setCellValue("");
row1Cell1.setCellStyle(headCellStyle);
XSSFCell row1Cell2 = row1.createCell(2);
row1Cell2.setCellValue("");
row1Cell2.setCellStyle(headCellStyle);
XSSFCell row1Cell3 = row1.createCell(3);
row1Cell3.setCellValue("");
row1Cell3.setCellStyle(headCellStyle);
XSSFCell row1Cell4 = row1.createCell(4);
row1Cell4.setCellValue("");
row1Cell4.setCellStyle(headCellStyle);
XSSFCell row1Cell5 = row1.createCell(5);
row1Cell5.setCellValue("");
row1Cell5.setCellStyle(headCellStyle);
XSSFCell row1Cell6 = row1.createCell(6);
row1Cell6.setCellValue("");
row1Cell6.setCellStyle(headCellStyle);
//起始行,结束行,起始列,结束列
CellRangeAddress region = new CellRangeAddress(0, 0, 0, 7);
sheet.addMergedRegion(region);
XSSFRow row2 = sheet.createRow(1);
XSSFCell row2Cell0 = row2.createCell(0);
row2Cell0.setCellValue("序号");
row2Cell0.setCellStyle(contentStyle);
XSSFCell row2Cell1 = row2.createCell(1);
row2Cell1.setCellValue("委托单号");
row2Cell1.setCellStyle(contentStyle);
XSSFCell row2Cell2 = row2.createCell(2);
row2Cell2.setCellValue("报告类型");
row2Cell2.setCellStyle(contentStyle);
XSSFCell row2Cell3 = row2.createCell(3);
row2Cell3.setCellValue("委托日期");
row2Cell3.setCellStyle(contentStyle);
XSSFCell row2Cell4 = row2.createCell(4);
row2Cell4.setCellValue("企业名称");
row2Cell4.setCellStyle(contentStyle);
XSSFCell row2Cell5 = row2.createCell(5);
row2Cell5.setCellValue("统一社会信用代码");
row2Cell5.setCellStyle(contentStyle);
XSSFCell row2Cell6 = row2.createCell(6);
row2Cell6.setCellValue("失败原因");
row2Cell6.setCellStyle(contentStyle);
// sheet.setColumnWidth(row2Cell6.getColumnIndex(), 356 * 50);
if (failEnterpriseList.isEmpty() && qyxxErrorList.isEmpty() && doubleReasonList.isEmpty()) {
return workbook;
}
int i=0;
if(doubleReasonList.size()>0){
for (i=0; i<doubleReasonList.size(); i++) { //(0-9 10条)
Map<String,Object> enterpriseVO = doubleReasonList.get(i);
XSSFRow row = sheet.createRow(i+2);
XSSFCell rowCell0 = row.createCell(0);
rowCell0.setCellValue(i+1);
rowCell0.setCellStyle(contentStyle);
XSSFCell rowCell1 = row.createCell(1);
rowCell1.setCellValue(entrustmentformNumber);
rowCell1.setCellStyle(contentStyle);
XSSFCell rowCell2 = row.createCell(2);
rowCell2.setCellValue(reportTypeContainsVersion);
rowCell2.setCellStyle(contentStyle);
XSSFCell rowCell3 = row.createCell(3);
rowCell3.setCellValue(entrustmentDate);
rowCell3.setCellStyle(contentStyle);
XSSFCell rowCell4 = row.createCell(4);
rowCell4.setCellValue(HbaseConvertUtil.getStringValue(enterpriseVO.get("qymc")));
rowCell4.setCellStyle(contentStyle);
XSSFCell rowCell5 = row.createCell(5);
rowCell5.setCellValue(HbaseConvertUtil.getStringValue(enterpriseVO.get("tyxydm")));
rowCell5.setCellStyle(contentStyle);
XSSFCell rowCell6 = row.createCell(6);
rowCell6.setCellValue(failEnterpriseReason+","+qyxxErrorResion);
rowCell6.setCellStyle(contentStyle);
}
}
int j=i;
if(failEnterpriseList.size()>0){
for (j = i; j<failEnterpriseList.size()+i; j++) { //(2条 10-11)
Map<String,Object> enterpriseVO = failEnterpriseList.get(j-i);
XSSFRow row = sheet.createRow(j+2);
XSSFCell rowCell0 = row.createCell(0);
rowCell0.setCellValue(j+1);
rowCell0.setCellStyle(contentStyle);
XSSFCell rowCell1 = row.createCell(1);
rowCell1.setCellValue(entrustmentformNumber);
rowCell1.setCellStyle(contentStyle);
XSSFCell rowCell2 = row.createCell(2);
rowCell2.setCellValue(reportTypeContainsVersion);
rowCell2.setCellStyle(contentStyle);
XSSFCell rowCell3 = row.createCell(3);
rowCell3.setCellValue(entrustmentDate);
rowCell3.setCellStyle(contentStyle);
XSSFCell rowCell4 = row.createCell(4);
rowCell4.setCellValue(HbaseConvertUtil.getStringValue(enterpriseVO.get("qymc")));
rowCell4.setCellStyle(contentStyle);
XSSFCell rowCell5 = row.createCell(5);
rowCell5.setCellValue(HbaseConvertUtil.getStringValue(enterpriseVO.get("tyxydm")));
rowCell5.setCellStyle(contentStyle);
XSSFCell rowCell6 = row.createCell(6);
rowCell6.setCellValue(failEnterpriseReason+","+qyxxErrorResion);
rowCell6.setCellStyle(contentStyle);
}
}
int k=j;
if(qyxxErrorList.size()>0){
for (k = j; k<qyxxErrorList.size()+j; k++) { //(2条 11-12)
Map<String,Object> enterpriseVO = qyxxErrorList.get(k-j);
XSSFRow row = sheet.createRow(k+2);
XSSFCell rowCell0 = row.createCell(0);
rowCell0.setCellValue(k+1);
rowCell0.setCellStyle(contentStyle);
XSSFCell rowCell1 = row.createCell(1);
rowCell1.setCellValue(entrustmentformNumber);
rowCell1.setCellStyle(contentStyle);
XSSFCell rowCell2 = row.createCell(2);
rowCell2.setCellValue(reportTypeContainsVersion);
rowCell2.setCellStyle(contentStyle);
XSSFCell rowCell3 = row.createCell(3);
rowCell3.setCellValue(entrustmentDate);
rowCell3.setCellStyle(contentStyle);
XSSFCell rowCell4 = row.createCell(4);
rowCell4.setCellValue(HbaseConvertUtil.getStringValue(enterpriseVO.get("qymc")));
rowCell4.setCellStyle(contentStyle);
XSSFCell rowCell5 = row.createCell(5);
rowCell5.setCellValue(HbaseConvertUtil.getStringValue(enterpriseVO.get("tyxydm")));
rowCell5.setCellStyle(contentStyle);
XSSFCell rowCell6 = row.createCell(6);
rowCell6.setCellValue(failEnterpriseReason+","+qyxxErrorResion);
rowCell6.setCellStyle(contentStyle);
}
}
sheet.autoSizeColumn((short)0); //调整第一列宽度
sheet.autoSizeColumn((short)1); //调整第二列宽度
sheet.autoSizeColumn((short)2); //调整第三列宽度
sheet.autoSizeColumn((short)3); //调整第四列宽度
sheet.autoSizeColumn((short)4); //调整第四列宽度
sheet.autoSizeColumn((short)5); //调整第四列宽度
sheet.autoSizeColumn((short)6); //调整第四列宽度
return workbook;
}
3.合并单元格及自适应宽度调整:
POI是apache提供的一个读写Excel文档的开源组件,在操作excel时常要合并单元格,合并单元格的方法是:
sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 2));
自适应列宽度(适合于英文字符字段):
sheet.autoSizeColumn(1);
sheet.autoSizeColumn(1, true);
这两种方式都是自适应列宽度,但是注意这个方法在后边的版本才提供,poi的版本不要太老。 注意:第一个方法在合并单元格的的单元格并不好使,必须用第二个方法(很适合于解决中文字段)
sheet.setColumnWidth(m, “列名”.getBytes().length*2*256);
这个方法是计算字符串的长度,以便设置列宽,该方法在解决中文的问题上比较好,前面两种方法对中文不好好用。。。。
还有在自适应宽度的时候,有时候遇到单元格是公式单元格,自适应不起作用,那是因为单元格存的是公式,并不是真正的数据,解决方法:
HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(sheet.getWorkbook());
CellValue cell71Val = evaluator.evaluate(cell71);
cell71.setCellValue(cell71Val.getNumberValue());
将格式化后的数据再次set进去,就是真正的值了。
二:把excel表导出: