spring读取、写入、后台接收、前后台导出excel。

引入

  1. <!-- poi office -->
  2. <dependency>
  3. <groupId>org.apache.poi</groupId>
  4. <artifactId>poi</artifactId>
  5. <version>3.16</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.apache.poi</groupId>
  9. <artifactId>poi-ooxml</artifactId>
  10. <version>3.16</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.apache.poi</groupId>
  14. <artifactId>poi-ooxml-schemas</artifactId>
  15. <version>3.16</version>
  16. </dependency>

读取

  1. package excelHelper;
  2. import org.apache.poi.ss.usermodel.*;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.InputStream;
  6. public class ReadExcel {
  7. public static void main(String[] args) throws Exception {
  8. InputStream is = new FileInputStream(new File("d://测试.xls"));
  9. //根据输入流创建Workbook对象
  10. Workbook wb = WorkbookFactory.create(is);
  11. //get到Sheet对象
  12. Sheet sheet = wb.getSheetAt(0);
  13. //这个必须用接口
  14. for(Row row : sheet){
  15. for(Cell cell : row){
  16. //cell.getCellType是获得cell里面保存的值的type
  17. //如Cell.CELL_TYPE_STRING
  18. switch(cell.getCellTypeEnum()){
  19. case BOOLEAN:
  20. //得到Boolean对象的方法
  21. System.out.print(cell.getBooleanCellValue()+" ");
  22. break;
  23. case NUMERIC:
  24. //先看是否是日期格式
  25. if(DateUtil.isCellDateFormatted(cell)){
  26. //读取日期格式
  27. System.out.print(cell.getDateCellValue()+" ");
  28. }else{
  29. //读取数字
  30. System.out.print(cell.getNumericCellValue()+" ");
  31. }
  32. break;
  33. case FORMULA:
  34. //读取公式
  35. System.out.print(cell.getCellFormula()+" ");
  36. break;
  37. case STRING:
  38. //读取String
  39. System.out.print(cell.getRichStringCellValue().toString()+" ");
  40. break;
  41. }
  42. }
  43. System.out.println("");
  44. }
  45. }
  46. }

写入

  1. public class SummaryHSSF {
  2. public static void main(String[] args) throws IOException {
  3. //创建Workbook对象(这一个对象代表着对应的一个Excel文件)
  4. //HSSFWorkbook表示以xls为后缀名的文件
  5. Workbook wb = new XSSFWorkbook();
  6. //Workbook wb2 = new HSSFWorkbook();//如果是xls文件,就用这个
  7. //获得CreationHelper对象,这个应该是一个帮助类
  8. CreationHelper helper = wb.getCreationHelper();
  9. //创建Sheet并给名字(表示Excel的一个Sheet)
  10. Sheet sheet1 = wb.createSheet("HSSF_Sheet_1");
  11. Sheet sheet2 = wb.createSheet("HSSF_Sheet_2");
  12. //Row表示一行Cell表示一列
  13. Row row = null;
  14. Cell cell = null;
  15. for(int i=0;i<60;i=i+2){
  16. //获得这个sheet的第i行
  17. row = sheet1.createRow(i);
  18. //设置行长度自动
  19. //row.setHeight((short)500);
  20. row.setHeightInPoints(20);
  21. //row.setZeroHeight(true);
  22. for(int j=0;j<25;j++){
  23. //设置每个sheet每一行的宽度,自动,根据需求自行确定
  24. sheet1.autoSizeColumn(j+1, true);
  25. //创建一个基本的样式
  26. CellStyle cellStyle = SummaryHSSF.createStyleCell(wb);
  27. //获得这一行的每j列
  28. cell = row.createCell(j);
  29. if(j==0){
  30. //设置文字在单元格里面的位置
  31. cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
  32. //先创建字体样式,并把这个样式加到单元格的字体里面
  33. cellStyle.setFont(createFonts(wb));
  34. //把这个样式加到单元格里面
  35. cell.setCellStyle(cellStyle);
  36. //给单元格设值
  37. cell.setCellValue(true);
  38. }else if(j==1){
  39. //设置文字在单元格里面的位置
  40. cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
  41. //设置这个样式的格式(Format)
  42. cellStyle = SummaryHSSF.setCellFormat(helper,cellStyle, "#,##0.0000");
  43. //先创建字体样式,并把这个样式加到单元格的字体里面
  44. cellStyle.setFont(createFonts(wb));
  45. //把这个样式加到单元格里面
  46. cell.setCellStyle(cellStyle);
  47. //给单元格设值
  48. cell.setCellValue(new Double(2008.2008));
  49. }else if(j==2){
  50. cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
  51. cellStyle.setFont(createFonts(wb));
  52. cell.setCellStyle(cellStyle);
  53. cell.setCellValue(helper.createRichTextString("RichString"+i+j));
  54. }else if(j==3){
  55. cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
  56. cellStyle = SummaryHSSF.setCellFormat(helper,cellStyle, "MM-yyyy-dd");
  57. cell.setCellStyle(cellStyle);
  58. cell.setCellValue(new Date());
  59. }else if(j==24){
  60. cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
  61. cellStyle.setFont(createFonts(wb));
  62. //设置公式
  63. cell.setCellFormula("SUM(E"+(i+1)+":X"+(i+1)+")");
  64. }else{
  65. cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
  66. cellStyle = SummaryHSSF.setFillBackgroundColors(cellStyle,IndexedColors.ORANGE.getIndex(),IndexedColors.ORANGE.getIndex(),FillPatternType.SOLID_FOREGROUND);
  67. cell.setCellStyle(cellStyle);
  68. cell.setCellValue(1);
  69. }
  70. }
  71. }
  72. //输出x
  73. OutputStream os = new FileOutputStream(new File("d://测试.xlsx"));
  74. wb.write(os);
  75. os.close();
  76. }
  77. /**
  78. * 边框
  79. * @param wb
  80. * @return
  81. */
  82. public static CellStyle createStyleCell(Workbook wb){
  83. CellStyle cellStyle = wb.createCellStyle();
  84. //设置一个单元格边框颜色
  85. cellStyle.setBorderBottom(BorderStyle.THIN);
  86. cellStyle.setBorderTop(BorderStyle.THIN);
  87. cellStyle.setBorderLeft(BorderStyle.THIN);
  88. cellStyle.setBorderRight(BorderStyle.THIN);
  89. //设置一个单元格边框颜色
  90. cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
  91. cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
  92. cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
  93. cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
  94. return cellStyle;
  95. }
  96. /**
  97. * 设置文字在单元格里面的位置
  98. * CellStyle.ALIGN_CENTER
  99. * CellStyle.VERTICAL_CENTER
  100. * @param cellStyle
  101. * @param halign
  102. * @param valign
  103. * @return
  104. */
  105. public static CellStyle setCellStyleAlignment(CellStyle cellStyle,HorizontalAlignment halign,VerticalAlignment valign){
  106. //设置上下
  107. cellStyle.setAlignment(HorizontalAlignment.GENERAL);
  108. //设置左右
  109. cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
  110. return cellStyle;
  111. }
  112. /**
  113. * 格式化单元格
  114. * 如#,##0.00,m/d/yy去HSSFDataFormat或XSSFDataFormat里面找
  115. * @param cellStyle
  116. * @param fmt
  117. * @return
  118. */
  119. public static CellStyle setCellFormat(CreationHelper helper,CellStyle cellStyle,String fmt){
  120. //还可以用其它方法创建format
  121. cellStyle.setDataFormat(helper.createDataFormat().getFormat(fmt));
  122. return cellStyle;
  123. }
  124. /**
  125. * 前景和背景填充的着色
  126. * @param cellStyle
  127. * @param bg IndexedColors.ORANGE.getIndex();
  128. * @param fg IndexedColors.ORANGE.getIndex();
  129. * @param fp CellStyle.SOLID_FOREGROUND
  130. * @return
  131. */
  132. public static CellStyle setFillBackgroundColors(CellStyle cellStyle, short bg, short fg, FillPatternType fp){
  133. cellStyle.setFillBackgroundColor(bg);
  134. cellStyle.setFillForegroundColor(fg);
  135. cellStyle.setFillPattern(fp);
  136. return cellStyle;
  137. }
  138. /**
  139. * 设置字体
  140. * @param wb
  141. * @return
  142. */
  143. public static Font createFonts(Workbook wb){
  144. //创建Font对象
  145. Font font = wb.createFont();
  146. //设置字体
  147. font.setFontName("黑体");
  148. //着色
  149. font.setColor(IndexedColors.BLUE.getIndex());
  150. //斜体
  151. font.setItalic(true);
  152. //字体大小
  153. font.setFontHeight((short)300);
  154. return font;
  155. }
  156. }

后端接收

  1. @RequestMapping(value = "/import", method = RequestMethod.POST)
  2. public String importLogisticsCcode(@RequestParam("fileName") MultipartFile file) throws Exception {
  3. // 获取文件名
  4. String fileName = file.getOriginalFilename();
  5. if (StringUtils.isEmpty(fileName)){
  6. return "文件不能为空";
  7. }
  8. // 获取文件后缀
  9. String prefix=fileName.substring(fileName.lastIndexOf("."));
  10. if (!prefix.toLowerCase().contains("xls") || !prefix.toLowerCase().contains("xlsx") ){
  11. return "文件格式异常,请上传Excel文件格式";
  12. }
  13. // 防止生成的临时文件重复-建议使用UUID
  14. final File excelFile = File.createTempFile(System.currentTimeMillis()+"", prefix);
  15. file.transferTo(excelFile);
  16. //由于2003和2007的版本所使用的接口不一样,所以这里统一用Workbook做兼容
  17. boolean isExcel2003 = prefix.toLowerCase().endsWith("xls")?true:false;
  18. Workbook workbook = null;
  19. if(isExcel2003){
  20. workbook = new HSSFWorkbook(new FileInputStream(excelFile));
  21. }else{
  22. workbook = new XSSFWorkbook(new FileInputStream(excelFile));
  23. }
  24. //Excel表中的内容
  25. List<Map<String,Object>> list = new ArrayList<>();
  26. Sheet sheet = workbook.getSheetAt(0);
  27. //这里重1开始,跳过了标题,直接从第二行开始解析
  28. for(int i=1; i<sheet.getLastRowNum()+1; i++) {
  29. Row row =sheet.getRow(i);
  30. //设置行格式和验证start 这里最好做成一个方法,免得代码多处复制
  31. if(row.getCell(0)!=null){
  32. row.getCell(0).setCellType(CellType.STRING);
  33. }
  34. if(row.getCell(1)!=null){
  35. row.getCell(1).setCellType(CellType.STRING);
  36. }
  37. if(row.getCell(2)!=null){
  38. row.getCell(2).setCellType(CellType.STRING);
  39. }
  40. String orderCode = row.getCell(0).getStringCellValue(); //订单编号
  41. if (StringUtils.isEmpty(orderCode)){
  42. return "第" + i+"行,第1列不能为空!";
  43. }
  44. String logisticsCompanyCode = row.getCell(1).getStringCellValue();
  45. if (StringUtils.isEmpty(logisticsCompanyCode)){
  46. return "第" + i+"行,第2列不能为空!";
  47. }
  48. String logisticsCode = row.getCell(2).getStringCellValue();
  49. if (StringUtils.isEmpty(logisticsCode)){
  50. return "第" + i+"行,第3列不能为空!";
  51. }
  52. //设置行格式和验证end
  53. //组装列表
  54. Map<String,Object> map = new HashMap<>();
  55. map.put("orderCode",orderCode);
  56. map.put("logisticsCompanyCode",logisticsCompanyCode);
  57. map.put("logisticsCode",logisticsCode);
  58. list.add(map);
  59. }
  60. //删除临时转换的文件
  61. if (excelFile.exists()) {
  62. excelFile.delete();
  63. }
  64. //list就是具体内容,剩下的就是自己处理具体业务了
  65. System.out.println("上传的内容就是这个了:" + list);
  66. }

前后端导出

controller设置header格式

  1. @GetMapping("/export")
  2. public void export(Long[] ids,HttpServletResponse response) throws IOException {
  3. BufferedInputStream bis = null;
  4. BufferedOutputStream bos = null;
  5. try {
  6. List<Order> order=orderService.findList(ids);
  7. Date currentTime = new Date();
  8. SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  9. String dataTime=formatter.format(currentTime);
  10. //获取收货单的字节数组
  11. byte[] content = orderService.exportOrders(order);
  12. InputStream is = new ByteArrayInputStream(content);
  13. String fileName = dataTime+"发货单";
  14. //页面弹层下载
  15. response.reset();
  16. response.setContentType("application/vnd.ms-excel;charset=utf-8");
  17. response.setHeader("Content-Disposition", "attachment;filename="
  18. + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
  19. ServletOutputStream out = response.getOutputStream();
  20. //流输出
  21. bis = new BufferedInputStream(is);
  22. bos = new BufferedOutputStream(out);
  23. byte[] buff = new byte[2048];
  24. int bytesRead;
  25. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
  26. out.write(buff, 0, bytesRead);
  27. }
  28. } catch (Exception e) {
  29. e.printStackTrace();
  30. }finally {
  31. //关流
  32. if (bis != null)
  33. bis.close();
  34. if (bos != null)
  35. bos.close();
  36. }
  37. }

service获取并设置excel的所有内容

  1. public byte[] exportOrders(List<Order> orders) {
  2. ByteArrayOutputStream os = new ByteArrayOutputStream();
  3. try {
  4. Date currentTime = new Date();
  5. SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
  6. String dataTime=formatter.format(currentTime);
  7. HSSFWorkbook workbook = new HSSFWorkbook();
  8. HSSFSheet sheet = workbook.createSheet("发货单");
  9. //设置字体
  10. HSSFFont font = workbook.createFont();
  11. font.setFontHeightInPoints((short)11); //字体高度
  12. font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //字体颜色
  13. font.setFontName("宋体"); //字体
  14. //生成标题样式
  15. HSSFCellStyle style = workbook.createCellStyle();
  16. style.setFont(font);
  17. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  18. style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  19. //创建第一行
  20. HSSFRow row = sheet.createRow(0);
  21. //设置行高
  22. row.setHeight((short)(30*20));
  23. HSSFCell cell = row.createCell(0);
  24. //设置大标题
  25. cell.setCellValue(dataTime+"发货单");
  26. cell.setCellStyle(style);
  27. row = sheet.createRow( 1);
  28. row.setHeight((short)(25*20));
  29. //设置小标题
  30. cell = row.createCell(0);
  31. cell.setCellValue("序号");
  32. cell.setCellStyle(style);
  33. cell = row.createCell(1);
  34. cell.setCellValue("订单编号");
  35. cell.setCellStyle(style);
  36. cell = row.createCell(2);
  37. cell.setCellValue("订单创建日期");
  38. cell.setCellStyle(style);
  39. cell = row.createCell(3);
  40. cell.setCellValue("会员用户名");
  41. cell.setCellStyle(style);
  42. cell = row.createCell(4);
  43. cell.setCellValue("商品名称");
  44. cell.setCellStyle(style);
  45. cell = row.createCell(5);
  46. cell.setCellValue("数量");
  47. cell.setCellStyle(style);
  48. cell = row.createCell(6);
  49. cell.setCellValue("单位");
  50. cell.setCellStyle(style);
  51. cell = row.createCell(7);
  52. cell.setCellValue("规格");
  53. cell.setCellStyle(style);
  54. cell = row.createCell(8);
  55. cell.setCellValue("商品分类");
  56. cell.setCellStyle(style);
  57. cell = row.createCell(9);
  58. cell.setCellValue("是否组合支付");
  59. cell.setCellStyle(style);
  60. cell = row.createCell(10);
  61. cell.setCellValue("人民币");
  62. cell.setCellStyle(style);
  63. cell = row.createCell(11);
  64. cell.setCellValue("积分类型");
  65. cell.setCellStyle(style);
  66. cell = row.createCell(12);
  67. cell.setCellValue("积分");
  68. cell.setCellStyle(style);
  69. cell = row.createCell(13);
  70. cell.setCellValue("收件人");
  71. cell.setCellStyle(style);
  72. cell = row.createCell(14);
  73. cell.setCellValue("收货手机号");
  74. cell.setCellStyle(style);
  75. cell = row.createCell(15);
  76. cell.setCellValue("收货人地址");
  77. cell.setCellStyle(style);
  78. cell = row.createCell(16);
  79. cell.setCellValue("邮编");
  80. cell.setCellStyle(style);
  81. cell = row.createCell(17);
  82. cell.setCellValue("状态");
  83. cell.setCellStyle(style);
  84. cell = row.createCell(18);
  85. cell.setCellValue("快递公司");
  86. cell.setCellStyle(style);
  87. cell = row.createCell(19);
  88. cell.setCellValue("快递单号");
  89. cell.setCellStyle(style);
  90. // 合并单元格
  91. CellRangeAddress cra =new CellRangeAddress(0, 0, 0, 19); // 起始行, 终止行, 起始列, 终止列
  92. //CellRangeAddress cra1 =new CellRangeAddress(1, 1, 9, 10); // 起始行, 终止行, 起始列, 终止列
  93. sheet.addMergedRegion(cra);
  94. //sheet.addMergedRegion(cra1);
  95. //设置列宽
  96. sheet.setColumnWidth(0,6*256);
  97. sheet.setColumnWidth(1,15*256);
  98. sheet.setColumnWidth(2,21*256);
  99. sheet.setColumnWidth(3,14*256);
  100. sheet.setColumnWidth(4,11*256);
  101. sheet.setColumnWidth(5,6*256);
  102. sheet.setColumnWidth(6,6*256);
  103. sheet.setColumnWidth(7,13*256);
  104. sheet.setColumnWidth(8,13*256);
  105. sheet.setColumnWidth(9,13*256);
  106. sheet.setColumnWidth(10,11*256);
  107. sheet.setColumnWidth(11,11*256);
  108. sheet.setColumnWidth(12,11*256);
  109. sheet.setColumnWidth(13,9*256);
  110. sheet.setColumnWidth(14,14*256);
  111. sheet.setColumnWidth(15,59*256);
  112. sheet.setColumnWidth(16,7*256);
  113. sheet.setColumnWidth(17,11*256);
  114. sheet.setColumnWidth(18,11*256);
  115. sheet.setColumnWidth(19,11*256);
  116. int rowNumber=0;
  117. //向单元格里填充数据
  118. for(int i=0;i<orders.size();i++){
  119. List<OrderItem> orderItems=orderItemService.getMerByOrderId(orders.get(i));
  120. for(int j=0; j<orderItems.size();j++){
  121. row=sheet.createRow( 2+rowNumber);
  122. row.setHeight((short)(20*20));
  123. row.createCell(0).setCellValue(1+rowNumber);
  124. row.createCell(1).setCellValue(orders.get(i).getSn());
  125. row.createCell(2).setCellValue(orders.get(i).getCreatedDate().toString());
  126. row.createCell(3).setCellValue(orders.get(i).getMember().getUsername());
  127. if(orderItems.get(j).getName().equals("茅台集团天朝上品1箱")){
  128. row.createCell(4).setCellValue("茅台集团天朝上品贵人酒");
  129. row.createCell(5).setCellValue(1*orderItems.get(j).getQuantity());
  130. }else if(orderItems.get(j).getName().equals("茅台集团天朝上品3箱")){
  131. row.createCell(4).setCellValue("茅台集团天朝上品贵人酒");
  132. row.createCell(5).setCellValue(3*orderItems.get(j).getQuantity());
  133. }else if(orderItems.get(j).getName().equals("茅台集团天朝上品5箱")){
  134. row.createCell(4).setCellValue("茅台集团天朝上品贵人酒");
  135. row.createCell(5).setCellValue(5*orderItems.get(j).getQuantity());
  136. }else if(orderItems.get(j).getName().equals("茅台集团天朝上品10箱")){
  137. row.createCell(4).setCellValue("茅台集团天朝上品贵人酒");
  138. row.createCell(5).setCellValue(10*orderItems.get(j).getQuantity());
  139. }else{
  140. row.createCell(4).setCellValue(orderItems.get(j).getName());
  141. row.createCell(5).setCellValue(orderItems.get(j).getQuantity());
  142. }
  143. row.createCell(6).setCellValue(orderItems.get(j).getSku().getProduct().getUnit());
  144. //规格
  145. List<SpecificationValue> specificationValues = orderItems.get(j).getSku().getSpecificationValues();
  146. if(!specificationValues.isEmpty()){
  147. StringBuilder sb= new StringBuilder();
  148. for(SpecificationValue specificationValue :specificationValues){
  149. sb.append(" ").append(specificationValue.getValue());
  150. }
  151. row.createCell(7).setCellValue(sb.toString());
  152. }else{
  153. row.createCell(7).setCellValue("");
  154. }
  155. //商品分类
  156. row.createCell(8).setCellValue(orderItems.get(j).getSku().getProduct().getProductCategory().getName());
  157. //组合支付
  158. Order.payType isExchangePoint = orderItems.get(j).getOrder().getIsExchangePoint();
  159. if(isExchangePoint.ordinal()==2){
  160. row.createCell(9).setCellValue("是");
  161. }else{
  162. row.createCell(9).setCellValue("否");
  163. }
  164. row.createCell(10).setCellValue(orders.get(i).getPrice().doubleValue());//人民币
  165. String currencyCode = orders.get(i).getCurrency().getCurrencyCode();
  166. if(!"CNY".equals(currencyCode)){
  167. row.createCell(11).setCellValue(currencyCode);//积分类型
  168. }
  169. row.createCell(12).setCellValue(orders.get(i).getExchangePoint().doubleValue());//积分
  170. row.createCell(13).setCellValue(orders.get(i).getConsignee());
  171. row.createCell(14).setCellValue(orders.get(i).getPhone());
  172. row.createCell(15).setCellValue(orders.get(i).getAreaName()+orders.get(i).getAddress());
  173. row.createCell(16).setCellValue(orders.get(i).getZipCode());
  174. row.createCell(17).setCellValue(getStart(orders.get(i).getStatus().toString()));
  175. rowNumber++;
  176. }
  177. }
  178. workbook.write(os);
  179. } catch (IOException e) {
  180. e.printStackTrace();
  181. }
  182. byte[] content = os.toByteArray();
  183. return content;
  184. }