java使用poi匯出excel例子
阿新 • • 發佈:2018-11-05
java匯出某個頁籤: 第一步:先在jsp新建一個匯出介面按鈕: <a id="export" class="mini-button" iconCls="icon-download" onclick="exportexcel();" plain="true">匯出</a> 第二步:在js中新建匯出方法: //匯出資料到EXCEL表 function exportexcel(){ var rows1 = treegrid.getRootNode(); var rows = rows1.children; var bi_id = ""; for(var i = 0 ;i<rows.length;i++){ if(i==0){ bi_id+="'"; bi_id+=rows[i].BI_ID.toString(); }else{ bi_id+="','"; bi_id+=rows[i].BI_ID.toString(); } } bi_id+="'"; var dp = mini.get("datePicker").value.format('yyyy-MM'); if(tabsName=="BI"){ var url1 = resources.webappName + "/projectTechnical/ExportExcelTechnical?bi_id=" + bi_id+"&dp="+dp; window.location.href = url1; }else if (tabsName=="IN"){ var url1 = resources.webappName + "/projectTechnical/ExportExcelTechnical_IN?bi_id=" + bi_id+"&dp="+dp; window.location.href = url1; }else{ var url1 = resources.webappName + "/projectTechnical/ExportExcelTechnical_FF?bi_id=" + bi_id+"&dp="+dp; window.location.href = url1; } } 第三步:在servlet新建一個ExportExcelTechnical檔案: package gdzc2015.servlet.projectTechnical; import gdzc2015.service.projectTechnical.projectTechnicalExpXls.TechnicalProjectExporter; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.sql.ResultSet; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.PrintSetup; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFFont; import org.apache.poi.xssf.usermodel.XSSFPrintSetup; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import com.bl.platform.tools.json.JSONArray; import com.bl.platform.tools.json.JSONException; import com.bl.platform.tools.json.JSONObject; import com.sdjxd.pms.platform.data.DbOper; @SuppressWarnings("serial") public class ExportExcelTechnical extends HttpServlet { private TechnicalProjectExporter rpexper = new TechnicalProjectExporter(); /** * Constructor of the object. */ public ExportExcelTechnical() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String bi_id = request.getParameter("bi_id"); String dp = request.getParameter("dp"); bi_id=bi_id.replace("'","'"); String year = dp.substring(0,4); String date = dp.substring(5,7); String sql = "SELECT a.bi_name,a.bi_id,a.bi_code,a.bi_no,a.bi_build_type,c.BUILD_STAGE,a.BI_BUDGET_NO,a.BI_BEGIN_DATE,a.BI_PID,a.BI_LEVEL,b.BI_TOTAL_INVEST,b.BI_PLAN_INVEST,d.START_DATE,d.PAUSE_DATE FROM " ; sql +="(select rownum px,bi_name,bi_id,bi_code,bi_no,bi_build_type,BI_BUDGET_NO,BI_BUDGET_APPROVAL,BI_BEGIN_DATE,BI_PID,BI_LEVEL from project_library start with bi_id in (" + bi_id + ") connect by prior bi_id = bi_pid order siblings by bi_no) a "; sql +=" left join (SELECT * FROM project_report where report_date ='" +date +"' and report_year = '"+year+"' and project_id in(SELECT bi_id FROM project_library where bi_type = 7)) b on b.project_id = a.bi_id "; sql +=" left join (SELECT DECODE(BUILD_STAGE,0,'預留空',1,'本年新建專案',2,'本年續建專案',3,'投運專案') BUILD_STAGE,bi_id FROM project_stage_config where bi_id in (SELECT bi_id FROM project_library where bi_type = 7)and build_date = '"+year+"') c on a.bi_id = c.bi_id "; sql +=" left join (select substr(start_date, 1, 10) start_date,substr(pause_date, 1,10) pause_date,bi_id from (select bi_id, max(start_date) start_date,max(pause_date) pause_date from project_cycle_config group by bi_id, pause_date) "; sql +=" where substr(start_date, 1, 7) <= '"+dp+"' and substr(nvl(pause_date, '9999-12-31'), 1, 7) >= '"+dp+"' and bi_id in(SELECT bi_id FROM project_library where bi_type = 7)) d on a.bi_id = d.bi_id "; sql += " where a.bi_level in (0,1) or a.bi_id in(select pcc.bi_id from project_cycle_config pcc where substr(pcc.start_date, 1, 7) <= '"+dp+"' and substr(nvl(pcc.pause_date, '9999-12-31'),1,7) >= '"+dp+"') order by a.px"; ResultSet rs; try { rs = DbOper.executeQuery(sql); List<Map<String,Object>> rows = new ArrayList<Map<String,Object>>(); while (rs.next()) { Map row = new HashMap(); for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { row.put(rs.getMetaData().getColumnName(i).toUpperCase(), rs.getObject(i)); } rows.add(row); } String [][] BiaoTi = { {"專案ID","父ID","層級","專案名稱","專案唯一編碼","專案排序編碼","建設型別","建設階段","概(預)算批准文號","開工日期","計劃投資","","項目錄入及終止時間",""}, {"","","","","","","","","","","計劃總投資","本年計劃投資","開始時間","停緩時間"}, {"BI_ID","BI_PID","BI_LEVEL","BI_NAME","BI_CODE","BI_NO","BI_BUILD_TYPE","BUILD_STAGE","BI_BUDGET_NO","BI_BEGIN_DATE","BI_TOTAL_INVEST","BI_PLAN_INVEST","START_DATE","PAUSE_DATE"} }; SXSSFWorkbook workbook = rpexper.exportExcel(BiaoTi,rows,""); String title = "生產技改專案"; String fileName = title + "-專案基本資訊" +".xlsx"; fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1"); // 取消亂碼 response.setContentType("octets/stream"); response.addHeader("Content-Disposition", "attachment;filename=" + fileName); OutputStream out = response.getOutputStream(); workbook.write(out); out.close(); System.out.println("匯出Excel"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } } 第四步:由於第三步引用了這個檔案;TechnicalProjectExporter()來畫表,所以加上這個檔案: package gdzc2015.service.projectTechnical.projectTechnicalExpXls; import gdzc2015.common.excel.reader.Interface.IExporter; import java.io.IOException; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.DataFormat; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.PrintSetup; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFFont; import org.apache.poi.xssf.usermodel.XSSFSheet; public class TechnicalProjectExporter implements IExporter{ /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public SXSSFWorkbook exportExcel(String[][] BiaoTi,List<Map<String,Object>> rows,String curDate){ SXSSFWorkbook workbook = new SXSSFWorkbook(); // 建立工作薄,相當於一個檔案 Sheet sheet = workbook.createSheet(); // 建立一個表 //sheet.setDefaultColumnWidth((short) 3); // 設定預設列寬 //sheet.setColumnWidth(0, 18 * 256); // 設定單位列列寬 sheet.setMargin(XSSFSheet.TopMargin, 0.64); // 頁邊距(上) sheet.setMargin(XSSFSheet.BottomMargin, 0.64); // 頁邊距(下) sheet.setMargin(XSSFSheet.LeftMargin, 0.64); // 頁邊距(左) sheet.setMargin(XSSFSheet.RightMargin, 0.64); // 頁邊距(右) PrintSetup ps = sheet.getPrintSetup(); ps.setPaperSize(PrintSetup.A4_PAPERSIZE); // 設定紙張大小 ps.setLandscape(true); // 列印方向,true:橫向,false:縱向(預設) // 標題樣式 CellStyle titleStyle = workbook.createCellStyle(); titleStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 水平居中 titleStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 垂直居中 // 標題字型 Font titleFont = workbook.createFont(); titleFont.setFontHeightInPoints((short) 14); // 字型大小 titleFont.setFontName("宋體"); titleStyle.setFont(titleFont); // 填報單位的樣式 CellStyle titleStyle_2 = workbook.createCellStyle(); titleStyle_2.setAlignment(XSSFCellStyle.ALIGN_RIGHT); // 水平居右 titleStyle_2.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 垂直居中 // 標題字型 Font titleFont_2 = workbook.createFont(); titleFont_2.setFontHeightInPoints((short) 11); titleFont_2.setFontName("宋體"); titleStyle_2.setFont(titleFont_2); // 填報單位的樣式 CellStyle titleStyle_u = workbook.createCellStyle(); titleStyle_u.setAlignment(XSSFCellStyle.ALIGN_LEFT); // 水平居左 titleStyle_u.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 垂直居中 // 標題字型 Font titleFont_u = workbook.createFont(); titleFont_u.setUnderline(XSSFFont.U_SINGLE); titleFont_u.setFontHeightInPoints((short) 11); titleFont_u.setFontName("宋體"); titleStyle_u.setFont(titleFont_u); // 表頭樣式 CellStyle headerStyle = workbook.createCellStyle(); headerStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 水平居中 headerStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 垂直居中 headerStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); // 下邊框 headerStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN); // 左邊框 headerStyle.setBorderTop(XSSFCellStyle.BORDER_THIN); // 上邊框 headerStyle.setBorderRight(XSSFCellStyle.BORDER_THIN); // 右邊框 headerStyle.setWrapText(true); // 設定多行顯示 //這兩句話是表示將表頭單元格格式設定為文字型,在後面只要呼叫-----.setDataFormat(format.getFormat("@"))的方法就可以將資料設定為文字型。 DataFormat format = workbook.createDataFormat(); headerStyle.setDataFormat(format.getFormat("@")); // 表頭字型 Font headerFont = workbook.createFont(); headerFont.setFontHeightInPoints((short) 9); headerFont.setFontName("宋體"); headerStyle.setFont(headerFont); // 資料樣式 CellStyle dataStyle = workbook.createCellStyle(); dataStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 水平居中 dataStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 垂直居中 dataStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); // 下邊框 dataStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN); // 左邊框 dataStyle.setBorderTop(XSSFCellStyle.BORDER_THIN); // 上邊框 dataStyle.setBorderRight(XSSFCellStyle.BORDER_THIN); // 右邊框 dataStyle.setDataFormat(format.getFormat("@")); //將資料單元格格式設定為文字型別 // 資料字型 Font dataFont = workbook.createFont(); dataFont.setFontHeightInPoints((short) 9); dataFont.setFontName("宋體"); dataStyle.setFont(dataFont); // 尾部樣式 CellStyle footStyle = workbook.createCellStyle(); footStyle.setAlignment(XSSFCellStyle.ALIGN_LEFT); // 水平居中 footStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 垂直居中 // 尾部字型 Font footFont = workbook.createFont(); footFont.setFontHeightInPoints((short) 11); footFont.setFontName("宋體"); footStyle.setFont(footFont); CellStyle commonStyle = workbook.createCellStyle(); commonStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); // 下邊框 commonStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN); // 左邊框 commonStyle.setBorderTop(XSSFCellStyle.BORDER_THIN); // 上邊框 commonStyle.setBorderRight(XSSFCellStyle.BORDER_THIN); // 右邊框 String tbdwmc = ""; String shr = ""; String tbr = ""; Object obj = rows.size()==0?"":rows.get(0).get("CREATEORG"); tbdwmc = obj==null?"":obj.toString(); String title = "生產技改專案"; // 表格標題行 Row row0 = sheet.createRow(0); row0.setHeight((short)(3 * 256)); Cell cell0_0 = row0.createCell(0); // 建立單元格,引數說明的是第幾個單元格 cell0_0.setCellStyle(titleStyle); cell0_0.setCellValue(title); // 設定單元格 和裡面的內容 Row row1 = sheet.createRow(1); row1.setHeight((short) (2 * 256)); Cell cell1_0 = row1.createCell(0); // 建立單元格,引數說明的是第幾個單元格 cell1_0.setCellStyle(titleStyle_2); cell1_0.setCellValue("填報單位: "); // 設定單元格 和裡面的內容 Cell cell1_2 = row1.createCell(2); // 建立單元格,引數說明的是第幾個單元格 cell1_2.setCellStyle(titleStyle_u); cell1_2.setCellValue(tbdwmc); // 設定單元格 和裡面的內容 sheet.setColumnWidth(0, 40*256); sheet.setColumnWidth(1, 40*256); sheet.setColumnWidth(2, 40*256); sheet.setColumnWidth(3, 40*256); sheet.setColumnWidth(4, 30*256); sheet.setColumnWidth(5, 30*256); Row row = null; Cell cell = null; for(int i = 2 ; i<5 ; i++){ row = sheet.createRow(i); row.setHeight((short)(2 * 256)); for(int j = 0 ;j < BiaoTi[i-2].length;j++){ cell = row.createCell(j); cell.setCellValue(BiaoTi[i-2][j]); cell.setCellStyle(headerStyle); } } sheet.getRow(4).setZeroHeight(true); // 合併單元格 sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 13)); // 合併大標題行 sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 3)); sheet.addMergedRegion(new CellRangeAddress(1, 1, 4, 13)); sheet.addMergedRegion(new CellRangeAddress(2, 3, 0, 0)); sheet.addMergedRegion(new CellRangeAddress(2, 3, 1, 1)); sheet.addMergedRegion(new CellRangeAddress(2, 3, 2, 2)); sheet.addMergedRegion(new CellRangeAddress(2, 3, 3, 3)); sheet.addMergedRegion(new CellRangeAddress(2, 3, 4, 4)); sheet.addMergedRegion(new CellRangeAddress(2, 3, 5, 5)); sheet.addMergedRegion(new CellRangeAddress(2, 3, 6, 6)); sheet.addMergedRegion(new CellRangeAddress(2, 3, 7, 7)); sheet.addMergedRegion(new CellRangeAddress(2, 3, 8, 8)); sheet.addMergedRegion(new CellRangeAddress(2, 3, 9, 9)); sheet.addMergedRegion(new CellRangeAddress(2, 2, 10, 11)); sheet.addMergedRegion(new CellRangeAddress(2, 2, 12, 13)); String[] names = BiaoTi[BiaoTi.length-1]; // 資料填充 for (int i = 0; i < rows.size(); i++) { Row dataRow = sheet.createRow(5 + i); Map<String,Object> project = rows.get(i); for (int j = 0; j <names.length; j++) { Cell dataCell = dataRow.createCell(j); dataCell.setCellStyle(dataStyle); obj = project.get(names[j]); dataCell.setCellValue(obj==null?"":obj.toString()); } } sheet.setColumnHidden(0,true); sheet.setColumnHidden(1,true); sheet.setColumnHidden(2,true); // // 表尾部 // int weiRowNum = rows.size() + 7; // Row weiRow = sheet.createRow(weiRowNum); // // Cell shr_c = weiRow.createCell(2); // shr_c.setCellStyle(footStyle); // shr_c.setCellValue("" + shr); // // Cell zbr_c = weiRow.createCell(11); // zbr_c.setCellStyle(footStyle); // zbr_c.setCellValue("" + tbr); //DateFormat df = new SimpleDateFormat("yyyy-MM"); //DateFormat df2 = new SimpleDateFormat("yyyy年MM月"); //String dateForStr = rows.getJSONObject(0).getString("CREATEDATE"); //Date date = df.parse(tbsj); //dateForStr = df2.format(date); /*XSSFCell tbsj_c = weiRow.createCell(20); tbsj_c.setCellStyle(footStyle); tbsj_c.setCellValue("填報時間:" + dateForStr); sheet.addMergedRegion(new CellRangeAddress(weiRowNum, weiRowNum, 2, 10)); // 合併尾部 sheet.addMergedRegion(new CellRangeAddress(weiRowNum, weiRowNum, 11, 19)); // 合併尾部 sheet.addMergedRegion(new CellRangeAddress(weiRowNum, weiRowNum, 20, 29)); // 合併尾部 */ return workbook; } }
對應的jar包下載地址:poi所有需要的jar下載(3.8版本)