使用poi实现导出excel数据表格

布满荆棘的人生 2022-06-02 07:15 492阅读 0赞

最近项目中要求技术实现导出商品订单的excel表格数据,功能虽然实现了,但是依旧两个小的技术点,没有实现

1,中文文件名称的编写,乱码后,数据是无法显示的.

2,条件查询时,Enum类型的参数没有传输到controller层.明天攻克以下吧..

使用maven构建项目的时候,需要使用pom.xml引入对应的jar包:

  1. <!--poi导出excel开始-->
  2. <dependency>
  3. <groupId>org.apache.poi</groupId>
  4. <artifactId>poi</artifactId>
  5. <version>3.15</version>
  6. </dependency>
  7. <!--poi导出excel结束-->

页面jsp实现.

  1. <div class="col-md-3" style="padding-left: 15px;">
  2. <button type="button" id="exportData" class="btn btn-search" style="width:45%">
  3. 导出数据
  4. </button>
  5. </div>

三个查询条件

  1. <label for="beginDate" class="col-md-4 control-label">开始日期</label>
  2. <div class="col-md-8">
  3. <input name="beginDate" id="beginDate" cssClass="form-control"
  4. style="height: 34px;border-radius: 4px;"
  5. οnclick="WdatePicker({dateFmt:'yyyy-MM-dd',readOnly:true,alwaysUseStartDate:true});"
  6. placeholder="请选择下单日期"
  7. value='<fmt:formatDate value="<%=new Date()%>" pattern="yyyy-MM-dd "/>'/>
  8. </div>
  9. </div>
  10. <div class="col-md-3">
  11. <label for="endDate" class="col-md-4 control-label">结束日期</label>
  12. <div class="col-md-8">
  13. <input name="endDate" id="endDate" cssClass="form-control"
  14. style="height: 34px;border-radius: 4px;"
  15. οnclick="WdatePicker({maxDate:'%y-%M-%d',readOnly:true,dateFmt:'yyyy-MM-dd',alwaysUseStartDate:true});"
  16. placeholder="请选择下单日期"
  17. value='<fmt:formatDate value="<%=new Date()%>" pattern="yyyy-MM-dd "/>'/>
  18. </div>
  19. </div>
  20. <div class="col-md-3">
  21. <label for="paymentType" class="col-md-4 control-label">支付方式</label>
  22. <div class="col-md-8">
  23. <select id="paymentType" name="paymentType" class="form-control">
  24. <option value="">***请选择支付方式***</option>
  25. <option value="icbc">第三方支付</option>
  26. <option value="cash">现金</option>
  27. <option value="onecard">食堂卡</option>
  28. <option value="bankcard">银行卡</option>
  29. </select>
  30. </div>
  31. </div>

js控制事件

  1. /*====================导出数据按钮开始============================*/
  2. $("#exportData").click(function(){
  3. var beginDate=$("#beginDate").val();
  4. var endDate=$("#endDate").val();
  5. var paymentType=$("#paymentType").val();
  6. window.location.href="${ctxPath}/payment/rpt/exportData.html?beginDate="+beginDate+"endDate="+endDate+"+paymentType="+paymentType;
  7. alert("下载完成");
  8. });
  9. /*====================导出数据按钮结束======================================*/

注意:此时使用ajax调用时,是没有执行的..必须使用window.location.href,具体原因后面有时间了再进行研究.

controller层数据获得和封装数据:

  1. /**
  2. * 统计payment流水
  3. *
  4. * @return
  5. * @throws Exception
  6. */
  7. @RequestMapping("exportData")
  8. @ResponseBody
  9. public Map<String, Object> exportData(HttpServletRequest request, HttpServletResponse response, Date beginDate, Date endDate, Enums.PaymentType paymentType, OrderBy orderBy, Pagination pageable) throws Exception {
  10. List<Long> storeIds = storeService.selectByUserId(this.getUser().getUserId());
  11. Long storeId = null;
  12. if (null != storeIds && storeIds.size() > 0) {
  13. storeId = storeIds.get(0);
  14. }
  15. //默认当前用户的ID;
  16. //单店模式暂时不用storeId去做查询条件
  17. ResultList<Payment> paymentResultList = this.paymentService.select(null, beginDate, endDate, getCompanyId(), storeId, paymentType, null, orderBy, pageable);
  18. Map<String, Object> map = SysStaticParam.resultMessage("获取信息成功!");
  19. //获取到所有的数据信息
  20. List<Payment> payments = paymentResultList.getData();
  21. //导出开始
  22. if (payments != null && payments.size() > 0) {
  23. //导出文件的标题
  24. /* String title = "abc.xls";*/
  25. String title="订单明细表"+beginDate+"--"+endDate+".xls";
  26. //设置表格标题行
  27. String[] headers = new String[]{"订单编号", "支付方式", "支付金额", "支付时间"};
  28. List<Object[]> dataList = new ArrayList<Object[]>();
  29. Object[] objs = null;
  30. for (Payment payment : payments) {//循环每一条数据
  31. objs = new Object[headers.length];
  32. objs[0] = payment.getOrderCode();//订单编号
  33. objs[1] = payment.getPaymentType();//支付方式
  34. objs[2] = payment.getPaymentPrice();//支付金额
  35. objs[3] = payment.getPaymentDate();//支付时间
  36. //数据添加到excel表格
  37. dataList.add(objs);
  38. }
  39. //使用流将数据导出
  40. OutputStream out = null;
  41. try {
  42. //防止中文乱码
  43. /*String headStr = "attachment; filename=\"" + title + "\"";*/
  44. /*String headStr = "attachment; filename=\"" + new String( title.getBytes("gb2312"), "ISO8859-1" ) + "\"";*/
  45. String headStr = "attachment; filename=\"" + new String( title.getBytes("gbk"), "utf-8" ) + "\"";
  46. response.setContentType("octets/stream");
  47. response.setContentType("APPLICATION/OCTET-STREAM");
  48. response.setHeader("Content-Disposition", headStr);
  49. out = response.getOutputStream();
  50. //ExportExcel ex = new ExportExcel(title, headers, dataList);//有标题
  51. ExportExcelSeedBack ex = new ExportExcelSeedBack(title, headers, dataList);//没有标题
  52. ex.export(out);
  53. } catch (Exception e) {
  54. e.printStackTrace();
  55. }
  56. map.put(SysStaticParam._RESULT, paymentResultList);
  57. }
  58. return map;
  59. }

工具类ExportExcelSeeBack.java

  1. package com.utp.pos.core.utils;
  2. import org.apache.poi.hssf.usermodel.*;
  3. import org.apache.poi.hssf.util.HSSFColor;
  4. import javax.servlet.http.HttpServletResponse;
  5. import java.io.IOException;
  6. import java.io.OutputStream;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. /**
  10. * Created by 623383562@qq.com on 2018/1/7.
  11. */
  12. public class ExportExcelSeedBack {
  13. //显示的导出表的标题
  14. private String title;
  15. //导出表的列名
  16. private String[] rowName ;
  17. private List<Object[]> dataList = new ArrayList<Object[]>();
  18. HttpServletResponse response;
  19. //构造方法,传入要导出的数据
  20. public ExportExcelSeedBack(String title,String[] rowName,List<Object[]> dataList){
  21. this.dataList = dataList;
  22. this.rowName = rowName;
  23. this.title = title;
  24. }
  25. /*
  26. * 导出数据
  27. * */
  28. public void export(OutputStream out) throws Exception{
  29. try{
  30. HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象
  31. HSSFSheet sheet = workbook.createSheet(title); // 创建工作表
  32. // 产生表格标题行
  33. // HSSFRow rowm = sheet.createRow(0);
  34. // HSSFCell cellTiltle = rowm.createCell(0);
  35. //sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】
  36. HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//获取列头样式对象
  37. HSSFCellStyle style = this.getStyle(workbook); //单元格样式对象
  38. // sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1)));//合并单元格
  39. // cellTiltle.setCellStyle(columnTopStyle);
  40. // cellTiltle.setCellValue(title);
  41. // 定义所需列数
  42. int columnNum = rowName.length;
  43. HSSFRow rowRowName = sheet.createRow(0); // 在索引2的位置创建行(最顶端的行开始的第二行)
  44. // 将列头设置到sheet的单元格中
  45. for(int n=0;n<columnNum;n++){
  46. HSSFCell cellRowName = rowRowName.createCell(n); //创建列头对应个数的单元格
  47. cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //设置列头单元格的数据类型
  48. HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
  49. cellRowName.setCellValue(text); //设置列头单元格的值
  50. cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式
  51. }
  52. //将查询出的数据设置到sheet对应的单元格中
  53. for(int i=0;i<dataList.size();i++){
  54. Object[] obj = dataList.get(i);//遍历每个对象
  55. HSSFRow row = sheet.createRow(i+1);//创建所需的行数(从第二行开始写数据)
  56. for(int j=0; j<obj.length; j++){
  57. HSSFCell cell = null; //设置单元格的数据类型
  58. if(j == 0){
  59. cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);
  60. cell.setCellValue(i+1);
  61. }else{
  62. cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);
  63. if(!"".equals(obj[j]) && obj[j] != null){
  64. cell.setCellValue(obj[j].toString()); //设置单元格的值
  65. }
  66. }
  67. cell.setCellStyle(style); //设置单元格样式
  68. }
  69. }
  70. //让列宽随着导出的列长自动适应
  71. for (int colNum = 0; colNum < columnNum; colNum++) {
  72. int columnWidth = sheet.getColumnWidth(colNum) / 256;
  73. for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
  74. HSSFRow currentRow;
  75. //当前行未被使用过
  76. if (sheet.getRow(rowNum) == null) {
  77. currentRow = sheet.createRow(rowNum);
  78. } else {
  79. currentRow = sheet.getRow(rowNum);
  80. }
  81. // if (currentRow.getCell(colNum) != null) {
  82. // HSSFCell currentCell = currentRow.getCell(colNum);
  83. // if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
  84. // int length = currentCell.getStringCellValue().getBytes().length;
  85. // if (columnWidth < length) {
  86. // columnWidth = length;
  87. // }
  88. // }
  89. // }
  90. if (currentRow.getCell(colNum) != null) {
  91. HSSFCell currentCell = currentRow.getCell(colNum);
  92. if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
  93. int length = 0;
  94. try {
  95. length = currentCell.getStringCellValue().getBytes().length;
  96. } catch (Exception e) {
  97. e.printStackTrace();
  98. }
  99. if (columnWidth < length) {
  100. columnWidth = length;
  101. }
  102. }
  103. }
  104. }
  105. if(colNum == 0){
  106. sheet.setColumnWidth(colNum, (columnWidth-2) * 256);
  107. }else{
  108. sheet.setColumnWidth(colNum, (columnWidth+4) * 256);
  109. }
  110. }
  111. if(workbook !=null){
  112. try{
  113. workbook.write(out);
  114. }catch (IOException e) {
  115. e.printStackTrace();
  116. }
  117. }
  118. }catch(Exception e){
  119. e.printStackTrace();
  120. }
  121. finally{
  122. out.close();
  123. }
  124. System.err.println("数据源大小:"+dataList.size());
  125. System.err.println("列数"+rowName.length);
  126. System.err.println(title);
  127. System.err.print("订单结束");
  128. }
  129. /*
  130. * 列头单元格样式
  131. */
  132. public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
  133. // 设置字体
  134. HSSFFont font = workbook.createFont();
  135. //设置字体大小
  136. font.setFontHeightInPoints((short)11);
  137. //字体加粗
  138. font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  139. //设置字体名字
  140. font.setFontName("Courier New");
  141. //设置样式;
  142. HSSFCellStyle style = workbook.createCellStyle();
  143. //设置底边框;
  144. style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  145. //设置底边框颜色;
  146. style.setBottomBorderColor(HSSFColor.BLACK.index);
  147. //设置左边框;
  148. style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  149. //设置左边框颜色;
  150. style.setLeftBorderColor(HSSFColor.BLACK.index);
  151. //设置右边框;
  152. style.setBorderRight(HSSFCellStyle.BORDER_THIN);
  153. //设置右边框颜色;
  154. style.setRightBorderColor(HSSFColor.BLACK.index);
  155. //设置顶边框;
  156. style.setBorderTop(HSSFCellStyle.BORDER_THIN);
  157. //设置顶边框颜色;
  158. style.setTopBorderColor(HSSFColor.BLACK.index);
  159. //在样式用应用设置的字体;
  160. style.setFont(font);
  161. //设置自动换行;
  162. style.setWrapText(false);
  163. //设置水平对齐的样式为居中对齐;
  164. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  165. //设置垂直对齐的样式为居中对齐;
  166. style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  167. return style;
  168. }
  169. /*
  170. * 列数据信息单元格样式
  171. */
  172. public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
  173. // 设置字体
  174. HSSFFont font = workbook.createFont();
  175. //设置字体大小
  176. //font.setFontHeightInPoints((short)10);
  177. //字体加粗
  178. //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  179. //设置字体名字
  180. font.setFontName("Courier New");
  181. //设置样式;
  182. HSSFCellStyle style = workbook.createCellStyle();
  183. //设置底边框;
  184. style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  185. //设置底边框颜色;
  186. style.setBottomBorderColor(HSSFColor.BLACK.index);
  187. //设置左边框;
  188. style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  189. //设置左边框颜色;
  190. style.setLeftBorderColor(HSSFColor.BLACK.index);
  191. //设置右边框;
  192. style.setBorderRight(HSSFCellStyle.BORDER_THIN);
  193. //设置右边框颜色;
  194. style.setRightBorderColor(HSSFColor.BLACK.index);
  195. //设置顶边框;
  196. style.setBorderTop(HSSFCellStyle.BORDER_THIN);
  197. //设置顶边框颜色;
  198. style.setTopBorderColor(HSSFColor.BLACK.index);
  199. //在样式用应用设置的字体;
  200. style.setFont(font);
  201. //设置自动换行;
  202. style.setWrapText(false);
  203. //设置水平对齐的样式为居中对齐;
  204. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  205. //设置垂直对齐的样式为居中对齐;
  206. style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  207. return style;
  208. }
  209. }

注意:突然发现此工具类中很多方法已经过时了.但是不影响使用,就没有更改.

1月8日更新:

乱码问题;

  1. //导出文件的标题,开始日期和结束日期的格式化
  2. String bDate = beginDate==null ? "初始日期" : DateUtil.getDateFormat(beginDate);
  3. String eDate = endDate==null ? "当前日期" : DateUtil.getDateFormat(endDate);
  4. String title="订单明细表"+bDate+" 至 "+eDate+".xls";
  5. //防止中文乱码
  6. String headStr = "attachment; filename=\"" + new String( title.getBytes("gb2312"), "ISO8859-1" ) + "\"";

因为中文乱码的时候,页面是下载失败的..不知道为啥

传参问题:

Enum类型的数据一样可以传参成功的.只是我个人的代码有问题.

看到windows.location.href=””页面.

  1. window.location.href="${ctxPath}/payment/rpt/exportData.html?beginDate="+beginDate+"endDate="+endDate+"+paymentType="+paymentType;

get方式的传参时,参数和参数之间是有”&”符号连接的…fk.

  1. window.location.href="${ctxPath}/payment/rpt/exportData.html?beginDate="+beginDate+"&endDate="+endDate+"+&paymentType="+paymentType;

另外修复了一下,使用

  1. objs[2] = payment.getPaymentType().getValue();//支付方式

payment是enum格式的,使用getValue()获取到String的值.

先就这样了…

发表评论

表情:
评论列表 (有 0 条评论,492人围观)

还没有评论,来说两句吧...

相关阅读