AJAX实现Excel文件下载

AJAX文件下载

===================================================================


2016年netty/mina/java nio视频教程java游戏服务器设计教程

互联网架构师教程: http://blog.csdn.net/pplcheer/article/details/71887910

互联网架构师视频课程 Dubbo ActiveMQ spring Netty MongoDB Jvm :http://blog.csdn.net/pplcheer/article/details/72794970

需要的加qq:1225462853,备注:程序员学习视频

其他视频都可以索要(Netty   NET    C++ 等等)

===================================================================


JQuery的ajax函数的返回类型只有xml、text、json、html等类型,没有“流”类型,所以我们要实现ajax下载,不能够使用相应的ajax函数进行文件下载。但可以用js生成一个form,用这个form提交参数,并返回“流”类型的数据。在实现过程中,页面也没有进行刷新。


注意此示例采用STRUTS2实现,没有采用Struts2内置的文件下载方法。

JS代码如下:

[html]  view plain  copy
  1. <script type="text/javascript">    
  2.    
  3.     function aClick () {  
  4.         $.ajax({    
  5.             type : "POST",  //提交方式    
  6.             url : "${pageContext.request.contextPath}/ajaxTest.action",//路径    
  7.             data : {    
  8.                 id: 1,  
  9.                 name:"testtt"  
  10.             },//数据,这里使用的是Json格式进行传输    
  11.             success : function(result) {//返回数据根据结果进行相应的处理    
  12.                 var form=$("<form>");//定义一个form表单  
  13.                 form.attr("style","display:none");  
  14.                 form.attr("target","");  
  15.                 form.attr("method","post");  
  16.                 form.attr("action","downloadTest.action");  
  17.                 var input1=$("<input>");  
  18.                 input1.attr("type","hidden");  
  19.                 input1.attr("name","exportData");  
  20.                 input1.attr("value",(new Date()).getMilliseconds());  
  21.                 $("body").append(form);//将表单放置在web中  
  22.                 form.append(input1);  
  23.                 form.submit();//表单提交   
  24.             }    
  25.         });  
  26.     }    
  27. </script>  

下图有两个超链接,第一个是通过AJAX调用下载ACTION的,第二个直接就是超链接调用ACTION 。

[html]  view plain  copy
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7. <script src='full/jquery.min.js'></script>  
  8. <title>Insert title here</title>  
  9. <script type="text/javascript">    
  10.    
  11.     function aClick () {  
  12.         $.ajax({    
  13.             type : "POST",  //提交方式    
  14.             url : "${pageContext.request.contextPath}/ajaxTest.action",//路径    
  15.             data : {    
  16.                 id: 1,  
  17.                 name:"testtt"  
  18.             },//数据,这里使用的是Json格式进行传输    
  19.             success : function(result) {//返回数据根据结果进行相应的处理    
  20.                 var form=$("<form>");//定义一个form表单  
  21.                 form.attr("style","display:none");  
  22.                 form.attr("target","");  
  23.                 form.attr("method","post");  
  24.                 form.attr("action","ajaxTest.action");  
  25.                 var input1=$("<input>");  
  26.                 input1.attr("type","hidden");  
  27.                 input1.attr("name","exportData");  
  28.                 input1.attr("value",(new Date()).getMilliseconds());  
  29.                 $("body").append(form);//将表单放置在web中  
  30.                 form.append(input1);  
  31.                 form.submit();//表单提交   
  32.             }    
  33.         });  
  34.     }    
  35. </script>  
  36. </head>  
  37. <body>  
  38.   
  39.     <br />  
  40.   
  41.     <h2>点击下载</h2>  
  42.    
  43.     <a href="javascript:void(0)" onclick="aClick()">文件下载</a>  
  44.   
  45.     <a href="ajaxTest.action?fileName=FCN301-Ver.1.1費用申請書.xls">文件下载(超链接)</a>  
  46.   
  47. </body>  
  48. </html>  


补充一个按钮的点击事件方法

[html]  view plain  copy
  1.    $( '#eventButton' ).click(function(){  
  2.        var dFrame=$("<iframe>");   
  3. dFrame.attr("style","display: none");   
  4. dFrame.attr("name","downloadFrame");   
  5. dFrame.attr("src","excelDownloadServlet?filePath=C:/TEMP/FCN301-Ver.1.1費用申請書.xls");  
  6. $("body").append(dFrame);      
  7.   
  8.    });  

ACTION类如下:(此ACTION类中也有一个下载的方法,都是共通的)

[java]  view plain  copy
  1. /** 
  2. * com.ppl.action.excelDol.java 
  3. * @author 作者 : pplsunny 
  4. * @version 创建时间:2017年4月8日 下午8:26:39 
  5. * 类说明 
  6. */  
  7.   
  8. package com.ppl.action;  
  9.   
  10. import java.io.BufferedInputStream;  
  11. import java.io.BufferedOutputStream;  
  12. import java.io.File;  
  13. import java.io.FileInputStream;  
  14. import java.io.FileNotFoundException;  
  15. import java.io.IOException;  
  16. import java.io.InputStream;  
  17. import java.io.OutputStream;  
  18.   
  19. import javax.servlet.http.HttpServletRequest;  
  20. import javax.servlet.http.HttpServletResponse;  
  21.   
  22. import org.apache.struts2.ServletActionContext;  
  23.   
  24. import com.opensymphony.xwork2.ActionSupport;  
  25. import com.ppl.test.WorkbookDemo;  
  26.   
  27. /** 
  28. *  XXXX 
  29. */  
  30. public class excelDol extends ActionSupport {  
  31.   
  32.     public String execute() throws Exception {  
  33.           
  34.         String filePath="G:/POI_JAVA/FCN301-Ver.1.1費用申請書.xls";  
  35.           
  36.         //下载到客户端  
  37.         HttpServletResponse response = ServletActionContext.getResponse();  
  38.         //download(filePath,response);  
  39.         WorkbookDemo.readTempleteExcel(filePath, response);  
  40.           
  41.         //1 获取表单数据  
  42.         HttpServletRequest request = ServletActionContext.getRequest();  
  43.         String id = request.getParameter("id");  
  44.         String name = request.getParameter("name");  
  45.         System.out.println(id+"--"+name);  
  46.         return NONE;  
  47.     }  
  48.       
  49.     private void download(String path, HttpServletResponse response) {    
  50.         try {    
  51.             // path是指欲下载的文件的路径。    
  52.             File file = new File(path);    
  53.             // 取得文件名。    
  54.             String filename = file.getName();   
  55.             String strName = new String(filename.getBytes("UTF-8"), "ISO-8859-1");    
  56.             // 以流的形式下载文件。    
  57.             InputStream fis = new BufferedInputStream(new FileInputStream(path));    
  58.             byte[] buffer = new byte[fis.available()];    
  59.             fis.read(buffer);    
  60.             fis.close();    
  61.             // 清空response    
  62.             response.reset();    
  63.             // 设置response的Header    
  64.             response.addHeader("Content-Disposition""attachment;filename="    
  65.                     + new String(filename.getBytes("UTF-8"), "ISO-8859-1"));    
  66.             response.addHeader("Content-Length""" + file.length());    
  67.             OutputStream toClient = new BufferedOutputStream(    
  68.                     response.getOutputStream());    
  69.             response.setContentType("application/vnd.ms-excel;charset=gb2312");    
  70.             toClient.write(buffer);    
  71.             toClient.flush();    
  72.             toClient.close();    
  73.         } catch (IOException ex) {    
  74.             ex.printStackTrace();    
  75.         }    
  76.     }    
  77.   
  78. }  

EXCEL文件操作类

[java]  view plain  copy
  1. package com.ppl.test;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.ByteArrayInputStream;  
  6. import java.io.ByteArrayOutputStream;  
  7. import java.io.FileInputStream;  
  8. import java.io.FileNotFoundException;  
  9. import java.io.FileOutputStream;  
  10. import java.io.IOException;  
  11. import java.io.InputStream;  
  12. import java.io.OutputStream;  
  13. import java.net.URLEncoder;  
  14. import java.text.DecimalFormat;  
  15. import java.text.SimpleDateFormat;  
  16. import java.util.Calendar;  
  17. import java.util.Date;  
  18. import java.util.Iterator;  
  19.   
  20. import javax.servlet.http.HttpServletResponse;  
  21.   
  22. import org.apache.poi.hssf.usermodel.HSSFCell;  
  23. import org.apache.poi.hssf.usermodel.HSSFDateUtil;  
  24. import org.apache.poi.hssf.usermodel.HSSFRow;  
  25. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  26. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  27. import org.apache.poi.poifs.filesystem.POIFSFileSystem;  
  28. import org.apache.poi.ss.usermodel.Cell;  
  29. import org.apache.poi.ss.usermodel.CellStyle;  
  30. import org.apache.poi.ss.usermodel.CreationHelper;  
  31. import org.apache.poi.ss.usermodel.Row;  
  32. import org.apache.poi.ss.usermodel.Sheet;  
  33. import org.apache.poi.ss.usermodel.Workbook;  
  34. import org.apache.poi.ss.usermodel.WorkbookFactory;  
  35. import org.apache.poi.ss.util.WorkbookUtil;  
  36.   
  37. public class WorkbookDemo {  
  38.   
  39.     /** 
  40.      * 创建工作簿 
  41.      * @throws IOException 
  42.      */  
  43.     public static void createWorkBook() throws IOException {  
  44.   
  45.         /** 
  46.          * 工作薄:  WorkBook是操作Excel的入口,Excel的文档对象,HSSFWorkbook(2003版本 ), XSSFWorkbook(2007版本)实现了该接口。 
  47.          *  HSSF对应xls格式,XSSF对应xlsx格式 
  48.          * ------------------------------------------------------------------ 
  49.          * Workbook wb = new XSSFWorkbook(); 
  50.          * FileOutputStream fileOut = new FileOutputStream("workbook.xlsx"); 
  51.          * wb.write(fileOut); 
  52.          * fileOut.close(); 
  53.          * ------------------------------------------------------------------ 
  54.          */  
  55.         final Workbook HSSFwb = new HSSFWorkbook();  
  56.   
  57.         /** 
  58.          * Sheet是在org.apache.poi.ss.usermodel包的接口,它是创建具有特定名称的高或低级别的电子表格的所有类的超接口。 
  59.          * 页:Sheet表示工作薄的分页。HSSFSheet, XSSFChartSheet, XSSFDialogsheet, XSSFSheet实现了该接口。 
  60.          * 索引以0开始,以workbook.getNumberOfSheets()-1结束 
  61.          */  
  62.         final String safeName = WorkbookUtil.createSafeSheetName("first sheet");  
  63.         final Sheet sheet = HSSFwb.createSheet(safeName);  
  64.   
  65.         //sheet.autoSizeColumn(6, true);  
  66.   
  67.         /** 
  68.          * 获取工作簿数量 
  69.          */  
  70.         final int sheetCount = HSSFwb.getNumberOfSheets();  
  71.         System.out.println("sheetCount: " + sheetCount);  
  72.   
  73.         /** 
  74.          * Row:表示页中的一行。HSSFRow, XSSFRow实现了该接口。 
  75.          * Row的索引以0开始(getFirstRowNum),以getLastRowNum结束 
  76.          */  
  77.         final Row row = sheet.createRow((short0);  
  78.   
  79.         /** 
  80.          * 得到的是最后一个不为空的行索引,真实行号是【getLastRowNum()+1】 
  81.          */  
  82.         final int rowNumReal = sheet.getLastRowNum();  
  83.   
  84.         /** 
  85.          * Cell:行中的一个单元格。HSSFCell, XSSFCell实现了该接口。 
  86.          * Cell的索引以0开始(getFirstCellNum),以getLastCellNum结束, 
  87.          */  
  88.         final Cell cell = row.createCell(0);  
  89.   
  90.         /** 
  91.          * 获取当前行中不为空的单元格数 
  92.          */  
  93.         final int cellNumReal = row.getPhysicalNumberOfCells();  
  94.   
  95.         /** 
  96.          * 空单元格返回对应的单元格类型 
  97.          */  
  98.         Cell cell2 = row.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);  
  99.         cell2 = row.getCell(4, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);  
  100.         cell2 = row.getCell(5, Row.MissingCellPolicy.RETURN_NULL_AND_BLANK);  
  101.   
  102.         //设置单元格的数据  
  103.         cell.setCellValue(1);  
  104.   
  105.         // Or do it on one line.   
  106.         row.createCell(1).setCellValue(1.2);  
  107.         row.createCell(2).setCellValue("This is a string 速度反馈链接");  
  108.         row.createCell(3).setCellValue(true);  
  109.   
  110.         //----------------------单元格赋值示例START------------------------------------------  
  111.         /** 
  112.          * 创建第十行 
  113.          */  
  114.         final Row rowTEN = sheet.createRow((short9);  
  115.   
  116.         // 填充日期类型的数据---未设置Cell Style   
  117.         rowTEN.createCell(1).setCellValue(new Date());  
  118.         // 另一种创建日期的方法  
  119.         rowTEN.createCell(2).setCellValue(Calendar.getInstance());  
  120.   
  121.         /** 
  122.          * 在第十行的单元格上创建单元格 
  123.          */  
  124.         final Cell cellOther = rowTEN.createCell(5);  
  125.         cellOther.setCellValue(new Date());  
  126.   
  127.         /** 
  128.          *  获取HSSF的辅助类 
  129.          */  
  130.         final CreationHelper createHelper = HSSFwb.getCreationHelper();  
  131.   
  132.         final CellStyle cellStyle = HSSFwb.createCellStyle();  
  133.   
  134.         // 填充日期类型的数据---已设置Cell Style  
  135.         final String timeFormat = "yyyy-MM-dd hh:mm:ss";  
  136.         cellStyle.setDataFormat(createHelper.createDataFormat().getFormat(timeFormat));  
  137.         final Cell cell7 = rowTEN.createCell(6);  
  138.         cell7.setCellValue(new Date());  
  139.         cell7.setCellStyle(cellStyle);  
  140.   
  141.         /** 
  142.          * 设置单元格宽度自适应,对中文支持不好 
  143.          */  
  144.         sheet.autoSizeColumn((short6);  
  145.   
  146.         //----------------------单元格赋值示例END------------------------------------------  
  147.         /** 
  148.          * 创建一个文件 命名为workbook.xls,默认创建到当前工程的根目录下 
  149.          */  
  150.         final FileOutputStream fileOut = new FileOutputStream("workbook2.xls");  
  151.   
  152.         /** 
  153.          * 把上面创建的工作簿输出到文件中  
  154.          */  
  155.         HSSFwb.write(fileOut);  
  156.   
  157.         /** 
  158.          * 关闭输出流  
  159.          */  
  160.         fileOut.close();  
  161.         HSSFwb.close();  
  162.   
  163.     }  
  164.   
  165.     /** 
  166.      * 使用POI读入excel工作簿文件  
  167.      * @throws Exception 
  168.      */  
  169.     public static void readWorkBook() throws Exception {  
  170.   
  171.         /** 
  172.          * 从文件流读取Excel 
  173.          */  
  174.         final InputStream inp = new FileInputStream("workbook1.xls");  
  175.   
  176.         /** 
  177.          * 根据上述创建的输入流 创建工作簿对象  
  178.          */  
  179.         final Workbook wb = WorkbookFactory.create(inp);  
  180.   
  181.         /** 
  182.          * 页Sheet是从0开始索引的  
  183.          */  
  184.         final Sheet sheet = wb.getSheetAt(0);  
  185.   
  186.         /** 
  187.          * 按名引用excel工作表 
  188.          * Sheet sheetByName = wb.getSheet("NAME"); 
  189.          */  
  190.   
  191.         /** 
  192.          * 获取工作簿的行数 
  193.          */  
  194.         final int rowNumReal = sheet.getLastRowNum();  
  195.         System.out.println("----------------------");  
  196.         System.out.println("rowNumReal-->" + rowNumReal);  
  197.         System.out.println("----------------------");  
  198.         final int cellNumReal = sheet.getRow(rowNumReal).getPhysicalNumberOfCells();  
  199.         System.out.println("cellNumReal-->" + cellNumReal);  
  200.   
  201.         //利用foreach循环 遍历sheet中的所有行   
  202.         int rowNum=0;  
  203.   
  204.         /** 
  205.          * 直接采用这种循环空行和空列是不会读取的, 
  206.          * 即当行有空行或者一行中有空单元格是,循环会跳过去 
  207.          */  
  208.         for (final Row row : sheet) {  
  209.             rowNum++;  
  210.             //遍历row中的所有方格   
  211.             for (final Cell cell : row) {  
  212.   
  213.                 final String valueT = getCellContentAsString(cell);  
  214.   
  215.                 System.out.println(cell.toString() + " ---> " + valueT);  
  216.             }  
  217.   
  218.             //每一个行输出之后换行   
  219.             System.out.println();  
  220.         }  
  221.   
  222.         System.out.println("----------------------");  
  223.         loopRowAndCell(sheet);  
  224.         System.out.println("rowNum-->"+rowNum);  
  225.         //关闭输入流   
  226.         inp.close();  
  227.     }  
  228.   
  229.     /** 
  230.      * 遍历一个工作簿中的行和列 
  231.      * 不包含空行和空列(无需对空行和空列做处理) 
  232.      * @param sheet 
  233.      * @throws Exception 
  234.      */  
  235.     public static void loopRealRowAndCell(final Sheet sheet) throws Exception {  
  236.   
  237.         /** 
  238.          * 遍历行 
  239.          */  
  240.         int rowno = 0;  
  241.         for (final Iterator itemRow = sheet.rowIterator(); itemRow.hasNext();) {  
  242.             final Row row = (Row) itemRow.next();  
  243.             rowno++;  
  244.             System.out.println("----------rowno----------" + rowno);  
  245.             /** 
  246.              * 遍历列 
  247.              */  
  248.             for (final Iterator itemCell = row.cellIterator(); itemCell.hasNext();) {  
  249.                 final Cell cell = (Cell) itemCell.next();  
  250.                 /** 
  251.                  * 获取单元格格式类型 
  252.                  * POI 3.15 beta 3. Use CellType.ERROR instead. 
  253.                  */  
  254.                 String cellValue = "";  
  255.                 switch (cell.getCellTypeEnum()) {  
  256.                 case STRING:// 字符串  
  257.                     cellValue = cell.getRichStringCellValue().getString().trim();  
  258.                     break;  
  259.                 case NUMERIC:// 数字  
  260.   
  261.                     //如果为时间格式的内容  
  262.                     if (HSSFDateUtil.isCellDateFormatted(cell)) {  
  263.                         final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  264.                         cellValue = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();  
  265.                         break;  
  266.                     } else {  
  267.   
  268.                         /** 
  269.                          * 解决科学计数法的问题 
  270.                          */  
  271.                         final Double d = cell.getNumericCellValue();  
  272.                         final DecimalFormat dformat = new DecimalFormat("#.##");  
  273.                         cellValue = dformat.format(d);  
  274.   
  275.                     }  
  276.   
  277.                     break;  
  278.                 case BOOLEAN:// Boolean  
  279.                     cellValue = String.valueOf(cell.getBooleanCellValue()).trim();  
  280.                     break;  
  281.                 case FORMULA:// 公式  
  282.   
  283.                     /** 
  284.                      * 解决公式的取值问题 
  285.                      */  
  286.                     try {  
  287.   
  288.                         /** 
  289.                          * 公式计算结果是纯数字 
  290.                          */  
  291.                         cellValue = String.valueOf(cell.getNumericCellValue());  
  292.                     } catch (final IllegalStateException e) {  
  293.   
  294.                         /** 
  295.                          * 公式计算结果是不是纯数字 
  296.                          */  
  297.                         cellValue = String.valueOf(cell.getRichStringCellValue());  
  298.                     }  
  299.   
  300.                     /** 
  301.                      * 这句获取的是计算公式 
  302.                      */  
  303.                     //cellValue = cell.getCellFormula() + "";  
  304.                     break;  
  305.   
  306.                 case BLANK: // 空值  
  307.                     cellValue = "BLANG";  
  308.                     break;  
  309.                 case ERROR: // 故障  
  310.                     cellValue = "N/A";  
  311.                     break;  
  312.                 default://未知类型  
  313.                     cellValue = "ERROR";  
  314.                 }  
  315.   
  316.                 System.out.println(" cellValue---> " + cellValue);  
  317.             }  
  318.         }  
  319.   
  320.     }  
  321.   
  322.     /** 
  323.      * 遍历一个工作簿中的行和列 
  324.      * 包含空行和空列(传统遍历,需要对空行和空列进行处理) 
  325.      * @param sheet 
  326.      * @throws Exception 
  327.      */  
  328.     public static void loopRowAndCell(final Sheet sheet) throws Exception {  
  329.   
  330.         /** 
  331.          * 得到的是最后一个不为空的行索引,真实行号是【getLastRowNum()+1】 
  332.          */  
  333.         final int rowNumReal = sheet.getLastRowNum();  
  334.   
  335.         /** 
  336.          * 遍历行 
  337.          */  
  338.         for (int rowIndex = 0; rowIndex <= rowNumReal; rowIndex++) {  
  339.   
  340.             /** 
  341.              * 获取当前行 
  342.              */  
  343.             final Row row = sheet.getRow(rowIndex);  
  344.   
  345.             /** 
  346.              * 空行处理 
  347.              */  
  348.             if (null == row) {  
  349.                 System.out.println(" BLANG ROW " + rowIndex);  
  350.                 continue;  
  351.             }  
  352.             /** 
  353.              * 取得当前行的列数 
  354.              */  
  355.             final int cellCount = row.getLastCellNum();  
  356.   
  357.             /** 
  358.              * 遍历列 
  359.              */  
  360.             for (int cellIndex = 0; cellIndex < cellCount; cellIndex++) {  
  361.                 /** 
  362.                  * 获取当前列,如果当前列不存在(为空)则返回一个单元格类型为空的单元格 
  363.                  */  
  364.                 final Cell cell = row.getCell(cellIndex, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);  
  365.   
  366.                 /** 
  367.                  * 空列处理 
  368.                  */  
  369.                 if (null == cell) {  
  370.                     System.out.println(" BLANG CELL " + cellIndex);  
  371.                     continue;  
  372.                 }  
  373.   
  374.                 /** 
  375.                  * 获取单元格格式类型 
  376.                  * POI 3.15 beta 3. Use CellType.ERROR instead. 
  377.                  */  
  378.                 String cellValue = "";  
  379.                 switch (cell.getCellTypeEnum()) {  
  380.                 case STRING:// 字符串  
  381.                     cellValue = cell.getRichStringCellValue().getString().trim();  
  382.                     break;  
  383.                 case NUMERIC:// 数字  
  384.   
  385.                     //如果为时间格式的内容  
  386.                     if (HSSFDateUtil.isCellDateFormatted(cell)) {  
  387.                         final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  388.                         cellValue = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();  
  389.                         break;  
  390.                     } else {  
  391.   
  392.                         /** 
  393.                          * 解决科学计数法的问题 
  394.                          */  
  395.                         final Double d = cell.getNumericCellValue();  
  396.                         final DecimalFormat dformat = new DecimalFormat("#.##");  
  397.                         cellValue = dformat.format(d);  
  398.   
  399.                     }  
  400.   
  401.                     break;  
  402.                 case BOOLEAN:// Boolean  
  403.                     cellValue = String.valueOf(cell.getBooleanCellValue()).trim();  
  404.                     break;  
  405.                 case FORMULA:// 公式  
  406.   
  407.                     /** 
  408.                      * 解决公式的取值问题 
  409.                      */  
  410.                     try {  
  411.   
  412.                         /** 
  413.                          * 公式计算结果是纯数字 
  414.                          */  
  415.                         cellValue = String.valueOf(cell.getNumericCellValue());  
  416.                     } catch (final IllegalStateException e) {  
  417.   
  418.                         /** 
  419.                          * 公式计算结果是不是纯数字 
  420.                          */  
  421.                         cellValue = String.valueOf(cell.getRichStringCellValue());  
  422.                     }  
  423.   
  424.                     /** 
  425.                      * 这句获取的是计算公式 
  426.                      */  
  427.                     //cellValue = cell.getCellFormula() + "";  
  428.                     break;  
  429.   
  430.                 case BLANK: // 空值  
  431.                     cellValue = "BLANG";  
  432.                     break;  
  433.                 case ERROR: // 故障  
  434.                     cellValue = "N/A";  
  435.                     break;  
  436.                 default://未知类型  
  437.                     cellValue = "ERROR";  
  438.                 }  
  439.   
  440.                 System.out.println(" cellValue---> " + cellValue);  
  441.             }  
  442.         }  
  443.   
  444.     }  
  445.   
  446.     /** 
  447.      *  
  448.      *解析一个单元格得到数据 
  449.      * @param cell 
  450.      * @return 
  451.      */  
  452.     private static String getCellContentAsString(final Cell cell) {  
  453.   
  454.         if (null == cell) {  
  455.             return "";  
  456.         }  
  457.   
  458.         /** 
  459.          * 获取单元格格式类型 
  460.          * POI 3.15 beta 3. Use CellType.ERROR instead. 
  461.          */  
  462.         String cellValue = "";  
  463.         switch (cell.getCellTypeEnum()) {  
  464.         case STRING:// 字符串  
  465.             cellValue = cell.getRichStringCellValue().getString().trim();  
  466.             break;  
  467.         case NUMERIC:// 数字  
  468.   
  469.             //如果为时间格式的内容  
  470.             if (HSSFDateUtil.isCellDateFormatted(cell)) {  
  471.                 final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  472.                 cellValue = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();  
  473.                 break;  
  474.             } else {  
  475.   
  476.                 /** 
  477.                  * 解决科学计数法的问题 
  478.                  */  
  479.                 final Double d = cell.getNumericCellValue();  
  480.                 final DecimalFormat dformat = new DecimalFormat("#.##");  
  481.                 cellValue = dformat.format(d);  
  482.   
  483.             }  
  484.   
  485.             break;  
  486.         case BOOLEAN:// Boolean  
  487.             cellValue = String.valueOf(cell.getBooleanCellValue()).trim();  
  488.             break;  
  489.         case FORMULA:// 公式  
  490.   
  491.             /** 
  492.              * 解决公式的取值问题 
  493.              */  
  494.             try {  
  495.   
  496.                 /** 
  497.                  * 公式计算结果是纯数字 
  498.                  */  
  499.                 cellValue = String.valueOf(cell.getNumericCellValue());  
  500.             } catch (final IllegalStateException e) {  
  501.   
  502.                 /** 
  503.                  * 公式计算结果是不是纯数字 
  504.                  */  
  505.                 cellValue = String.valueOf(cell.getRichStringCellValue());  
  506.             }  
  507.   
  508.             /** 
  509.              * 这句获取的是计算公式 
  510.              */  
  511.             //cellValue = cell.getCellFormula() + "";  
  512.             break;  
  513.   
  514.         case BLANK: // 空值  
  515.             cellValue = "BLANG";  
  516.             break;  
  517.         case ERROR: // 故障  
  518.             cellValue = "N/A";  
  519.             break;  
  520.         default://未知类型  
  521.             cellValue = "";  
  522.         }  
  523.   
  524.         return cellValue;  
  525.     }  
  526.   
  527.     /** 
  528.      *  
  529.      * 读取已有Excel作为模板进行数据操作 
  530.      * @param filePAth 模板路径 
  531.      * @return -1:filePAth error; 
  532.      * @throws IOException  
  533.      * @throws FileNotFoundException  
  534.      */  
  535.     public static int readTempleteExcel(final String filePAth,HttpServletResponse response) throws FileNotFoundException, IOException {  
  536.   
  537.         if ((filePAth == null) || filePAth.trim().isEmpty()) {  
  538.             return -1;  
  539.         }  
  540.   
  541.         /** 
  542.          *  先读取模板 ,使用POIFSFileSystem对象构造的新HSSFWorkbook对象。 
  543.          */  
  544.         final POIFSFileSystem POIfs = new POIFSFileSystem(new FileInputStream(filePAth));  
  545.   
  546.         /** 
  547.          * 基于模板创建workbook  
  548.          */  
  549.         final HSSFWorkbook workbook = new HSSFWorkbook(POIfs);  
  550.   
  551.         /** 
  552.          * 如果模板存在多页的话可以分别取到  
  553.          */  
  554.         final HSSFSheet sheet_1st = workbook.getSheetAt(0);  
  555.   
  556.         //------------------------  
  557.         // 第一页,第一行   
  558.         final HSSFRow row = sheet_1st.getRow(0);  
  559.   
  560.         // 取第一个单元格   
  561.         final HSSFCell cell = row.getCell(0);  
  562.   
  563.         // 获取单元格字符串值   
  564.         final String cellValue = cell.getStringCellValue();  
  565.   
  566.         System.out.println(cellValue);  
  567.   
  568.         //final String path = "G:/POI_JAVA/demo.xls";  
  569.   
  570.         // 输出Excel   
  571.         HttpServletResponse newresponse=response;  
  572.         try {  
  573.               
  574.             ByteArrayOutputStream os = new ByteArrayOutputStream();  
  575.             workbook.write(os);// HSSFWorkbook写入流  
  576.              byte[] content = os.toByteArray();  
  577.             InputStream is = new ByteArrayInputStream(content);  
  578.               
  579.             //文件名字符编码转换  
  580.             //String strName = new String(filename.getBytes("UTF-8"), "ISO-8859-1");  
  581.             // 设置请求  
  582.             // 设置response参数,可以打开下载页面  
  583.             newresponse.reset();  
  584.                 
  585.             newresponse.setContentType("application/octet-stream");  
  586.             newresponse.setHeader("Content-Disposition""attachment;filename=" + URLEncoder.encode("aa.xls""UTF-8"));  
  587.   
  588.             OutputStream outputStream = newresponse.getOutputStream();// 打开流  
  589.               
  590.             BufferedInputStream bis = null;  
  591.             BufferedOutputStream bos = null;  
  592.               
  593.             bis = new BufferedInputStream(is);  
  594.             bos = new BufferedOutputStream(outputStream);  
  595.             byte[] buff = new byte[2048];  
  596.             int bytesRead;  
  597.             // Simple read/write loop.  
  598.             while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
  599.               bos.write(buff, 0, bytesRead);  
  600.             }  
  601.   
  602.             if (bis != null){  
  603.                  bis.close();  
  604.             }  
  605.   
  606.             if (bos != null){  
  607.                 bos.close();  
  608.             }  
  609.             outputStream.flush();// 刷新流  
  610.             outputStream.close();// 关闭流  
  611.   
  612.             workbook.close();  
  613.               
  614.         } catch (final IOException e) {  
  615.             // TODO Auto-generated catch block  
  616.             e.printStackTrace();  
  617.         }  
  618.   
  619.         return 0;  
  620.     }  
  621. }  


==================

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值