利用poi实现table表格导出excel
生活随笔
收集整理的這篇文章主要介紹了
利用poi实现table表格导出excel
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
思路:把table轉成json數據傳到后臺(需要用到jquery.tabletojson.min.js),json轉成list<list<String>>類型。利用poi導出excel
需要先導入poi jar包
前臺代碼:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>POI</title> <meta http-equiv="pragma" content="no-cache"> <span id="transmark"></span><meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/jquery.tabletojson.js"></script> <script type="text/javascript"> function exportExcel(fileName,tableId){ var table = $("#"+tableId).tableToJSON(); console.log(table); var json = JSON.stringify(table); var nodes = $("#"+tableId+" thead tr").children(); var headers = ""; $.each(nodes,function(i,item){ headers += item.innerHTML+","; }) //調用post方法 post('${ctx}/user/p2pUserInformation/exportExcel', {fileName :fileName,headers:headers,json:json});}function post(url, params) {var temp = document.createElement("form");temp.action = url;temp.method = "post";temp.style.display = "none";for (var x in params) {var opt = document.createElement("input");opt.name = x;opt.value = params[x];temp.appendChild(opt);}document.body.appendChild(temp);temp.submit();return temp;} </script> </head> <body> <table id="test"> <thead><tr><td>序號</td><td>姓名/td><td>name</td></tr> </thead><tr><td>1</td><td>張三</td><td>zhangsan</td></tr> <tr><td>2</td><td>李四</td><td>lisi</td></tr> <tr><td>3</td><td>王五</td><td>wangwu</td></tr> </table> <button οnclick="formSubmit('ceshi','test')">Export excel 2</button><br><br> </body> </html>后臺servlet: import java.io.IOException;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;import testExport.ExportExcel;public class TestJsonServlet extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//json字符串String jsonStr = request.getParameter("json");//表格表頭String sheaders = request.getParameter("headers");//表格標題名String title = request.getParameter("fileName");//表格文件名String fileName = request.getParameter("fileName")+".xls";ExportExcel ex = new ExportExcel();ex.export(jsonStr,sheaders,fileName,title, response, request);}}
ExportExcel.java package testExport;import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List;import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.swing.JOptionPane;import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFClientAnchor; import org.apache.poi.hssf.usermodel.HSSFComment; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFPatriarch; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;/*** 利用開源組件POI3.0.2動態導出EXCEL文檔* * @version v1.0* @param <T>* 應用泛型,代表任意一個符合javabean風格的類* 注意這里為了簡單起見,boolean型的屬性xxx的get器方式為getXxx(),而不是isXxx()* byte[]表jpg格式的圖片數據*/ public class ExportExcel{//文件分隔符"\"(在 UNIX 系統中是“/”)public static final String FILE_SEPARATOR = System.getProperties().getProperty("file.separator");/*** @param jsonStr* json字符串* @param sheaders* 表格表頭* @param fileName* 文件名XXX.xls* @param title* 表格標題名*/public void export(String jsonStr,String sheaders,String fileName,String title,HttpServletResponse response,HttpServletRequest request) {try {// 將json字符串轉換為json對象JSONArray jsonArray = new JSONArray(jsonStr); String[] headers= sheaders.substring(0,sheaders.length()-1).split(",");System.out.println(sheaders.substring(0,sheaders.length()-1));int iSize = jsonArray.length();List<List> list = new ArrayList<List>();for (int i = 0; i < iSize; i++) {List<String> line = new ArrayList<String>();JSONObject jsonObject = jsonArray.getJSONObject(i);System.out.println(jsonObject.toString()+"-----");Iterator iterator = jsonObject.keys();String value = null;int j=0;while (iterator.hasNext()) {iterator.next();value = jsonObject.getString(headers[j]);//表格內容line.add(value);j++;System.out.println(value);}list.add(line);}for(List<String> line:list){for(String s:line){System.out.print(s+"\t");}System.out.println();}String docsPath = request.getSession().getServletContext().getRealPath("exportExcel");//文件路徑String filePath = docsPath + FILE_SEPARATOR + fileName;System.out.println(filePath);OutputStream out = new FileOutputStream(filePath);exportExcel(title,headers, list, out);out.close();JOptionPane.showMessageDialog(null, "導出成功!");System.out.println("excel導出成功!");//下載download(filePath, response);} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (FileNotFoundException e) {// TODO: handle exceptione.printStackTrace();} catch (IOException e) {// TODO: handle exceptione.printStackTrace();}}/*** 這是一個通用的方法,利用了JAVA的反射機制,可以將放置在JAVA集合中并且符號一定條件的數據以EXCEL 的形式輸出到指定IO設備上* * @param title* 表格標題名* @param headers* 表格屬性列名數組* @param list* 需要顯示的數據集合* @param out* 與輸出設備關聯的流對象,可以將EXCEL文檔導出到本地文件或者網絡中*/private void exportExcel(String title, String[] headers,List<List> list, OutputStream out) {// 聲明一個工作薄HSSFWorkbook workbook = new HSSFWorkbook();// 生成一個表格HSSFSheet sheet = workbook.createSheet(title);// 設置表格默認列寬度為15個字節sheet.setDefaultColumnWidth((short) 15);// 生成一個樣式HSSFCellStyle style = workbook.createCellStyle();// 設置這些樣式style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);style.setBorderBottom(HSSFCellStyle.BORDER_THIN);style.setBorderLeft(HSSFCellStyle.BORDER_THIN);style.setBorderRight(HSSFCellStyle.BORDER_THIN);style.setBorderTop(HSSFCellStyle.BORDER_THIN);style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 生成一個字體HSSFFont font = workbook.createFont();font.setColor(HSSFColor.VIOLET.index);font.setFontHeightInPoints((short) 12);font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 把字體應用到當前的樣式style.setFont(font);// 生成并設置另一個樣式HSSFCellStyle style2 = workbook.createCellStyle();style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);style2.setBorderRight(HSSFCellStyle.BORDER_THIN);style2.setBorderTop(HSSFCellStyle.BORDER_THIN);style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 生成另一個字體HSSFFont font2 = workbook.createFont();font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);// 把字體應用到當前的樣式style2.setFont(font2);// 聲明一個畫圖的頂級管理器HSSFPatriarch patriarch = sheet.createDrawingPatriarch();// 定義注釋的大小和位置,詳見文檔HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,0, 0, 0, (short) 4, 2, (short) 6, 5));// 設置注釋內容comment.setString(new HSSFRichTextString("可以在POI中添加注釋!"));// 設置注釋作者,當鼠標移動到單元格上是可以在狀態欄中看到該內容.comment.setAuthor("leno");// 產生表格標題行HSSFRow row = sheet.createRow(0);for (short i = 0; i < headers.length; i++) {HSSFCell cell = row.createCell(i);cell.setCellStyle(style);HSSFRichTextString text = new HSSFRichTextString(headers[i]);cell.setCellValue(text);}// 遍歷集合數據,產生數據行for(int i=0;i<list.size();i++){List<String> line = list.get(i);row = sheet.createRow(i+1);for(int j=0;j<line.size();j++){HSSFCell cell = row.createCell(j);cell.setCellStyle(style2);String value = line.get(j);try {// 判斷值的類型后進行強制類型轉換String textValue = null;// 其它數據類型都當作字符串簡單處理textValue = value.toString();// 如果不是圖片數據,就利用正則表達式判斷textValue是否全部由數字組成if (textValue != null) {HSSFRichTextString richString = new HSSFRichTextString(textValue);HSSFFont font3 = workbook.createFont();font3.setColor(HSSFColor.BLUE.index);richString.applyFont(font3);cell.setCellValue(richString);}} catch (SecurityException e) {e.printStackTrace();} finally {// 清理資源}}}try {workbook.write(out);} catch (IOException e) {e.printStackTrace();}}private void download(String path, HttpServletResponse response) {try {// path是指欲下載的文件的路徑。File file = new File(path);// 取得文件名。String filename = file.getName();// 以流的形式下載文件。InputStream fis = new BufferedInputStream(new FileInputStream(path));byte[] buffer = new byte[fis.available()];fis.read(buffer);fis.close();// 清空responseresponse.reset();// 設置response的Headerresponse.addHeader("Content-Disposition", "attachment;filename="+ new String(filename.getBytes()));response.addHeader("Content-Length", "" + file.length());OutputStream toClient = new BufferedOutputStream(response.getOutputStream());response.setContentType("application/vnd.ms-excel;charset=gb2312");toClient.write(buffer);toClient.flush();toClient.close();} catch (IOException ex) {ex.printStackTrace();}}}
總結
以上是生活随笔為你收集整理的利用poi实现table表格导出excel的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 金融风控-- >客户流失预警模型-- >
- 下一篇: 国产机开始在海外大卖了?网友:简直是火得