Apache的POI常用api
目前常見讀寫Excel的工具類開源javaAPI有兩種方式,
一個是JXL(Java Excel API) 官網(wǎng)地址:http://jexcelapi.sourceforge.net/
一個是Apache的POI(Poor Obfuscation Implementation)官網(wǎng)地址:http://poi.apache.org/
POI支持微軟的OLE2格式文件Office 2003及以下版本;同時支持微軟的OOXML(Office Open XML)標(biāo)準(zhǔn),也就是Office 2007以上版本。JXL只能實現(xiàn)對Excel 2003以下版本的支持。
POI使用HSSF對象操作OLE2格式Excel,文件后綴為.xls的;使用XSSF、SXSSF對象操作OOXML格式Excel,文件后綴為.xlsx的。
對于OLE2版本的Excel,一個Sheet工作表它的行最多支持到65536行,列支持到256列;
對于OOXML版本的Excel,一個Sheet工作表它的行支持到1048576行,列支持到16384列。
核心API:
數(shù)據(jù)限制:
Excel2003 2007、2010
列: 255 16384
行: 65535 1048576
=================== 基礎(chǔ) ===================
// 創(chuàng)建excel(工作簿) 使用接口的方式來創(chuàng)建
Workbook wb = new HSSFWorkbook();
新建工作簿:
HSSFWorkbook wb = new HSSFWorkbook();
打開工作簿:
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(xlsFile));
建立新的sheet對象:
HSSFSheet sheet = wb.createSheet("我的第一個工作簿");
選擇第一個工作簿:
HSSFSheet sheet = wb.getSheetAt(0);
設(shè)置工作簿的名稱:
wb.setSheetName(0, "我的第一個工作簿");
創(chuàng)建行對象:
HSSFRow nRow = null;
nRow = sheet.createRow(1); //第2行
指定列 創(chuàng)建單元格對象:
HSSFCell nCell = null;
nCell = nRow.createCell((short)(2)); //第3列
指定列 創(chuàng)建單元格對象:
nCell.setCellValue("我是單元格");
// 獲取到樣式的對象
CellStyle style = wb.createCellStyle();
// 創(chuàng)建字體對象
Font font = wb.createFont();
// 設(shè)置字體大小
font.setFontHeightInPoints((short) 16);
// 設(shè)置字體的名稱
font.setFontName("楷體");
// 設(shè)置字體
style.setFont(font);
設(shè)置樣式 注意:樣式不能重復(fù)設(shè)置
nCell.setCellStyle(leftStyle(wb));
文件下載方法1:
先在服務(wù)器產(chǎn)生臨時文件,再下載臨時文件。
關(guān)閉保存excel文件
FileOutputStream fOut = new FileOutputStream(xlsFile); //創(chuàng)建xls文件,無內(nèi)容 0字節(jié)
wb.write(fOut); //寫內(nèi)容,xls文件已經(jīng)可以打開
fOut.flush(); //刷新緩沖區(qū)
fOut.close(); //關(guān)閉
文件下載方法2:
//7.生成excel文件
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); //生成流對象
wb.write(byteArrayOutputStream); //將excel寫入流
//工具類,封裝彈出下載框:
String outFile = "生產(chǎn)廠家通訊錄.xls";
DownloadBaseAction down = new DownloadBaseAction();
down.download(byteArrayOutputStream, response, outFile);
文件下載方法3:(適用于struts2)
ServletActionContext.getResponse().setContentType("application/octet-stream");
String returnName = ServletActionContext.getResponse().encodeURL( new String("購銷合同.xls".getBytes(), "ISO-8859-1"));
ServletActionContext.getResponse().addHeader("Content-Disposition", "attachment;filename=" + returnName);
wb.write(ServletActionContext.getResponse().getOutputStream());
文件下載方法4:
//下載文件
response.setContentType("application/octet-stream");
String returnName = response.encodeURL( new String("生產(chǎn)廠家通訊錄.xls".getBytes(), "ISO-8859-1"));
response.addHeader("Content-Disposition", "attachment;filename=" + returnName);
wb.write(response.getOutputStream());
字體修飾:
//設(shè)置單元格樣式
private HSSFCellStyle leftStyle(HSSFWorkbook wb){
HSSFCellStyle curStyle = wb.createCellStyle();
HSSFFont curFont = wb.createFont(); //設(shè)置字體
//curFont.setFontName("Times New Roman"); //設(shè)置英文字體
curFont.setFontName("微軟雅黑"); //設(shè)置英文字體
curFont.setCharSet(HSSFFont.DEFAULT_CHARSET); //設(shè)置中文字體,那必須還要再對單元格進行編碼設(shè)置
curFont.setFontHeightInPoints((short)10); //字體大小
curFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //加粗
curStyle.setFont(curFont);
curStyle.setBorderTop(HSSFCellStyle.BORDER_THICK); //粗實線
curStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //實線
curStyle.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM); //比較粗實線
curStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); //實線
curStyle.setWrapText(true); //換行
curStyle.setAlignment(HSSFCellStyle.ALIGN_RIGHT); //橫向具右對齊
curStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //單元格垂直居中
return curStyle;
}
=================== web環(huán)境 ===================
設(shè)置打印方向:默認縱向
PrintSetup ps = sheet.getPrintSetup();
ps.setLandscape(true); //橫向打印
自適應(yīng)列寬:
//bug 對中文支持不好,列寬不夠?qū)?br>for(int i=0 ;i<titles.length;i++){
sheet.autoSizeColumn((short)i);
}
設(shè)置行高:
nRow.setHeightInPoints(18);
設(shè)置列寬:
sheet.setColumnWidth((short)colNo, (short)(256*8));
設(shè)置每列默認寬度:
sheet.setDefaultColumnWidth((short) 20);
設(shè)置標(biāo)題:
將第一行作為標(biāo)題,即每頁都打印此行 sheetN,startCol,stopCol,startRow,stopRow
wb.setRepeatingRowsAndColumns(0,1,8,0,1);
頁腳:
HSSFFooter footer = sheet.getFooter();
footer.setRight("第"+HSSFFooter.page()+"頁 共"+HSSFFooter.numPages()+"頁 "); //頁數(shù)
工具類-單元格自適應(yīng)高度:
float height = pioUtil.getCellAutoHeight(extcproducts, 12f);
nRow.setHeightInPoints(height); //(一行字+行之間的間隙)*行數(shù)
分頁:
// POI分頁符有BUG,必須在模板文件中插入一個分頁符,然后再此處刪除預(yù)設(shè)的分頁符;最后在下面重新設(shè)置分頁符。
// sheet.setAutobreaks(false);
// int iRowBreaks[] = sheet.getRowBreaks();
// sheet.removeRowBreak(3);
// sheet.removeRowBreak(4);
// sheet.removeRowBreak(5);
// sheet.removeRowBreak(6);
sheet.setRowBreak(行數(shù)); //在第startRow行設(shè)置分頁符
==出貨表:
合并單元格:
//縱向合并單元格
Region region = null;
region = new Region(curRow-1, (short)(1), curRow-1+3, (short)1);
sheet.addMergedRegion(region);
//橫向合并單元格
CellRangeAddress
sheet.addMergedRegion(new CellRangeAddress(開始行,結(jié)束行,開始列,結(jié)束列));
// 橫向居中
style.setAlignment(CellStyle.ALIGN_CENTER);
// 縱向居中
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
文件直接輸出:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); //生成流對象
wb.write(byteArrayOutputStream); //將excel寫入流
HttpServletResponse response = ServletActionContext.getResponse();
//工具類,封裝彈出下載框:
DownloadBaseAction down = new DownloadBaseAction();
down.download(byteArrayOutputStream, response, outFile);
獲取模板:
int curRow = 0; //當(dāng)前行
int colNo = 1; //當(dāng)前列
//得到模板路徑
String rootPath = UtilFuns.getROOTPath();
String xlsFile = rootPath + "/make/xlsprint/tOUTPRODUCT.xls";
//新建臨時目錄,存放excel /root/web/tmpfile/yyyy-mm-dd/...
String filePath = "/web/tmpfile/" + UtilFuns.sysDate()+"/";
File tmpDir = new File(rootPath + filePath);
if(!tmpDir.exists()){
tmpDir.mkdirs(); //創(chuàng)建多級目錄
}
FileUtil fu = new FileUtil();
String sFile = fu.newFile(rootPath+filePath, "outproduct.xls"); //防止文件并發(fā)訪問
String outFile = rootPath+filePath+sFile; //輸出文件
==合同打印:
1、 分頁
sheet.setRowBreak(當(dāng)前行); //設(shè)置分頁符
2、怎么插入一個圖片
HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); //add picture
pioUtil.setPicture(wb, patriarch, rootPath+"make/xlsprint/logo.jpg", curRow, 2, curRow+4, 2);
3、怎么插入一條線
pioUtil.setLine(wb, patriarch, curRow, 2, curRow, 8); //draw line
4、設(shè)置數(shù)值類型
nCell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
5、設(shè)置前導(dǎo)符
HSSFDataFormat format = wb.createDataFormat();
return format.getFormat("\"¥\"#,###,##0.00"); // 設(shè)置格式
6、設(shè)置公式
nCell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
nCell.setCellFormula("F11*H11");
nCell.setCellFormula("F"+String.valueOf(curRow)+"*H"+String.valueOf(curRow));
nCell.setCellFormula("SUM(I"+String.valueOf(curRow-4)+":I"+String.valueOf(curRow-1)+")");
7、工具類:替換等量空格
fixSpaceStr(String str,int len)
8、業(yè)務(wù)要求:
1)同一個廠家的貨物才能打印到同一個頁面
List<ContractProduct> oList = oDao.find("from ContractProduct o where o.contract.id='"+contractId+"' order by o.factory.id,o.orderNo");
//廠家不同另起新頁打印,除去第一次的比較
if(oProduct.getFactory().getFactoryName().equals(oldFactory)){
}
2)打印可以選擇打印一款貨物,還是兩款貨物
if(contract.getPrintStyle().equals("2")){
}
9、數(shù)據(jù)和業(yè)務(wù)分離
//填寫每頁的內(nèi)容,之后在循環(huán)每頁讀取打印
Map<String,String> pageMap = null;
List<Map> pageList = new ArrayList(); //打印頁
==報運打印:
wb.cloneSheet(0); //復(fù)制sheet0工作簿,名字會自動重命名
1 package cn.itcast.export.util; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.IOException; 7 import java.net.URLEncoder; 8 9 import javax.servlet.ServletOutputStream; 10 import javax.servlet.http.HttpServletResponse; 11 12 import org.apache.struts2.ServletActionContext; 13 14 import sun.misc.BASE64Encoder; 15 16 public class DownloadUtil { 17 18 /** 19 * @param filePath 要下載的文件路徑 20 * @param returnName 返回的文件名 21 * @param response HttpServletResponse 22 * @param delFlag 是否刪除文件 23 */ 24 protected void download(String filePath,String returnName,HttpServletResponse response,boolean delFlag){ 25 this.prototypeDownload(new File(filePath), returnName, response, delFlag); 26 } 27 28 29 /** 30 * @param file 要下載的文件 31 * @param returnName 返回的文件名 32 * @param response HttpServletResponse 33 * @param delFlag 是否刪除文件 34 */ 35 protected void download(File file,String returnName,HttpServletResponse response,boolean delFlag){ 36 this.prototypeDownload(file, returnName, response, delFlag); 37 } 38 39 /** 40 * @param file 要下載的文件 41 * @param returnName 返回的文件名 42 * @param response HttpServletResponse 43 * @param delFlag 是否刪除文件 44 */ 45 public void prototypeDownload(File file,String returnName,HttpServletResponse response,boolean delFlag){ 46 // 下載文件 47 FileInputStream inputStream = null; 48 ServletOutputStream outputStream = null; 49 try { 50 if(!file.exists()) return; 51 response.reset(); 52 //設(shè)置響應(yīng)類型 PDF文件為"application/pdf",WORD文件為:"application/msword", EXCEL文件為:"application/vnd.ms-excel"。 53 response.setContentType("application/octet-stream;charset=utf-8"); 54 55 //設(shè)置響應(yīng)的文件名稱,并轉(zhuǎn)換成中文編碼 56 //returnName = URLEncoder.encode(returnName,"UTF-8"); 57 returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1")); //保存的文件名,必須和頁面編碼一致,否則亂碼 58 59 //attachment作為附件下載;inline客戶端機器有安裝匹配程序,則直接打開;注意改變配置,清除緩存,否則可能不能看到效果 60 response.addHeader("Content-Disposition", "attachment;filename="+returnName); 61 62 //將文件讀入響應(yīng)流 63 inputStream = new FileInputStream(file); 64 outputStream = response.getOutputStream(); 65 int length = 1024; 66 int readLength=0; 67 byte buf[] = new byte[1024]; 68 readLength = inputStream.read(buf, 0, length); 69 while (readLength != -1) { 70 outputStream.write(buf, 0, readLength); 71 readLength = inputStream.read(buf, 0, length); 72 } 73 } catch (Exception e) { 74 e.printStackTrace(); 75 } finally { 76 try { 77 outputStream.flush(); 78 } catch (IOException e) { 79 e.printStackTrace(); 80 } 81 try { 82 outputStream.close(); 83 } catch (IOException e) { 84 e.printStackTrace(); 85 } 86 try { 87 inputStream.close(); 88 } catch (IOException e) { 89 e.printStackTrace(); 90 } 91 //刪除原文件 92 93 if(delFlag) { 94 file.delete(); 95 } 96 } 97 } 98 99 /** 100 * by tony 2013-10-17 101 * @param byteArrayOutputStream 將文件內(nèi)容寫入ByteArrayOutputStream 102 * @param response HttpServletResponse 寫入response 103 * @param returnName 返回的文件名 104 */ 105 public void download(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName) throws IOException{ 106 response.setContentType("application/octet-stream;charset=utf-8"); 107 //returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1")); //保存的文件名,必須和頁面編碼一致,否則亂碼 108 String agent = ServletActionContext.getRequest().getHeader("user-agent");//客戶端瀏覽器版本 109 returnName = encodeDownloadFilename(returnName,agent ); 110 111 response.addHeader("Content-Disposition", "attachment;filename=" + returnName); 112 response.setContentLength(byteArrayOutputStream.size()); 113 114 ServletOutputStream outputstream = response.getOutputStream(); //取得輸出流 115 byteArrayOutputStream.writeTo(outputstream); //寫到輸出流 116 byteArrayOutputStream.close(); //關(guān)閉 117 outputstream.flush(); //刷數(shù)據(jù) 118 } 119 120 /** 121 * 下載文件時,針對不同瀏覽器,進行附件名的編碼 122 * @param filename 下載文件名 123 * @param agent 客戶端瀏覽器 124 * @return 編碼后的下載附件名 125 * @throws IOException 126 */ 127 public String encodeDownloadFilename(String filename, String agent) throws IOException{ 128 if(agent.contains("Firefox")){ // 火狐瀏覽器 129 filename = "=?UTF-8?B?"+new BASE64Encoder().encode(filename.getBytes("utf-8"))+"?="; 130 }else{ // IE及其他瀏覽器 131 filename = URLEncoder.encode(filename,"utf-8"); 132 } 133 return filename; 134 } 135 }

浙公網(wǎng)安備 33010602011771號