java使用org.apache.poi读取与保存EXCEL文件

时间:2021-01-02 20:23:56

 

一、读EXCEL文件

  1 package com.ruijie.wis.cloud.utils;
  2 
  3 import java.io.FileInputStream;
  4 import java.io.FileNotFoundException;
  5 import java.io.IOException;
  6 import java.io.InputStream;
  7 import java.text.DecimalFormat;
  8 import java.util.ArrayList;
  9 import java.util.HashMap;
 10 import java.util.Iterator;
 11 import java.util.List;
 12 import java.util.Map;
 13 
 14 import org.apache.poi.hssf.usermodel.HSSFCell;
 15 import org.apache.poi.ss.usermodel.Cell;
 16 import org.apache.poi.ss.usermodel.CellValue;
 17 import org.apache.poi.ss.usermodel.FormulaEvaluator;
 18 import org.apache.poi.ss.usermodel.Row;
 19 import org.apache.poi.xssf.usermodel.XSSFCell;
 20 import org.apache.poi.xssf.usermodel.XSSFCellStyle;
 21 import org.apache.poi.xssf.usermodel.XSSFFont;
 22 import org.apache.poi.xssf.usermodel.XSSFRow;
 23 import org.apache.poi.xssf.usermodel.XSSFSheet;
 24 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 25 import org.slf4j.Logger;
 26 import org.slf4j.LoggerFactory;
 27 
 28 public class ProjectImportUtil {
 29 public ProjectImportUtil() {
 30     String fileName = "D:\tst.xlsx";
 31   InputStream input = new FileInputStream(fileName);     
 32 }
 33 
 34 /* 导入销售数据 ,excel2007格式 */
 35 public List<Map<String,Object>> importSaleXml(InputStream input, String industry) { 
 36 List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
 37 DecimalFormat df =new DecimalFormat("#0");
 38 
 39 try { 
 40 XSSFWorkbook wb = new XSSFWorkbook(input); // Excel 2003 使用wb = new HSSFWorkbook(input);

41 FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
 42 int index_name = 0;  43 int index_province = 0;  44 int index_city = 0;  45 int index_acs = 0;  46 int index_aps = 0;  47 int index_zuozhi = 0;  48 String industry_name = industry;  49 XSSFSheet sheet = wb.getSheet(industry_name);  50 if(sheet == null) {  51 logger.warn("importSaleXml - industy: " + industry_name + " not exist!");  52 wb.close();  53 return null;  54 }  55 Iterator<Row> rows = sheet.rowIterator();  56 
 57 while (rows.hasNext()) {  58   Row row = rows.next();  59   if(row.getRowNum() == 0) { // 查找关心的数据所在列号
 60   Iterator<Cell> cells = row.cellIterator();  61   while (cells.hasNext()) {  62     Cell cell = cells.next();  63     String title = getCellValue(cell,evaluator);  64     if(title.equals("最终客户名称")) {  65       index_name = cell.getColumnIndex();  66     } else if(title.equals("省份")) {  67       index_province = cell.getColumnIndex();  68     } else if(title.equals("城市")) {  69       index_city = cell.getColumnIndex();  70     } else if(title.equals("AC系列")) {  71       index_acs = cell.getColumnIndex();  72     } else if(title.equals("AP系列")) {  73       index_aps = cell.getColumnIndex();  74     } else if(title.equals("卓智客户名称")) {  75       index_zuozhi = cell.getColumnIndex();  76   }  77   }  78 }  79 
 80   Cell cell_name = row.getCell(index_name);  81   Cell cell_province = row.getCell(index_province);  82   Cell cell_city = row.getCell(index_city);  83   Cell cell_acs = row.getCell(index_acs);  84   Cell cell_aps = row.getCell(index_aps);  85   String projectName = getCellValue(cell_name,evaluator);  86   String province = getCellValue(cell_province,evaluator);  87   String city = getCellValue(cell_city,evaluator);  88   String acs = getCellValue(cell_acs,evaluator);  89   String aps = getCellValue(cell_aps,evaluator);  90 
 91   Map<String,Object> salevalue = new HashMap<String, Object>();  92   salevalue.put("projectName", projectName);  93   salevalue.put("industry_name", industry_name);  94   if(province != null) {    95     salevalue.put("province", province);  96   }  97   if(city != null) {  98     salevalue.put("city", city);  99   } 100   if(acs != null) {   101     salevalue.put("acs", acs); 102   } 103   if(aps != null) { 104     salevalue.put("aps", aps); 105 
106   } 107 
108   result.add(salevalue); 109 } 110   wb.close(); 111 } catch (Exception e) { 112   logger.error(e.toString(),e); 113 } 114   return result; 115 } 116 
117 //根据cell中的类型来返回数据 
118 public String getCellValue(Cell cell, FormulaEvaluator evaluator) { 119   if(cell == null) { 120     return null; 121   } 122   CellValue cellValue = evaluator.evaluate(cell); 123   if(cellValue == null) { 124     return null; 125   } 126   switch (cellValue.getCellType()) { 127   case HSSFCell.CELL_TYPE_NUMERIC: 128   return cell.getNumericCellValue() + ""; 129   case HSSFCell.CELL_TYPE_STRING: 130   return cell.getStringCellValue() + ""; 131   case HSSFCell.CELL_TYPE_BOOLEAN: 132   return cell.getBooleanCellValue() + ""; 133   case HSSFCell.CELL_TYPE_FORMULA: 134   return cell.getCellFormula(); 135   default: 136   return null; 137 } 138 } 139 
140 }

 

二、写EXCEL文件

  1 XSSFWorkbook wb=new XSSFWorkbook();
  2 DeviceAlarmUtil outputResult = new DeviceAlarmUtil();
  3 wb = outputResult.outConfigExceptionResult(wb, "配置告警信息", configAlarmList);
  4 response.setContentType("application/msexcel");
  5 response.setHeader( "Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1" ) ); 
  6            
  7 ServletOutputStream os = null;
  8 try {
  9     os = response.getOutputStream();
 10     //写到输出流
 11      wb.write(os);
 12 } catch (FileNotFoundException e) {
 13      e.printStackTrace();
 14 } catch (IOException e) {
 15      e.printStackTrace();
 16 } catch (Throwable e) {
 17      e.printStackTrace();
 18 } finally {
 19      if (wb != null) {
 20          try {
 21              wb.close();
 22          } catch (IOException e) {
 23              throw new Exception("IO错误,无法导出结果");
 24          }
 25      }
 26      if (os != null) {
 27          try {
 28            os.flush();
 29             os.close();
 30          } catch (IOException e) {
 31             throw new Exception("IO错误,无法导出结果");
 32          }
 33      }
 34 }
 35 
 36 
 37 public XSSFWorkbook outConfigExceptionResult(XSSFWorkbook wb, String sheetName, List<Map<String, Object>> sheetResult){
 38         XSSFSheet sheet=wb.createSheet(sheetName);
 39         XSSFRow row=sheet.createRow(0);
 40         CellStyle cellStyle =wb.createCellStyle(); 
 41         // 设置这些样式 
 42         cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); 
 43         cellStyle.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index);
 44         cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
 45         cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); 
 46         cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN); 
 47         cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); 
 48         cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
 49         XSSFFont font = wb.createFont();
 50         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
 51         cellStyle.setFont(font);
 52         
 53         XSSFCell cell = row.createCell((short) 0);
 54         cell.setCellValue("客户名称"); 
 55         cell.setCellStyle(cellStyle);
 56         sheet.setColumnWidth(0, 5500);
 57         cell = row.createCell((short) 1);
 58         cell.setCellValue("AC MAC"); 
 59         cell.setCellStyle(cellStyle);
 60         sheet.setColumnWidth(1, 5000);
 61         cell = row.createCell((short) 2);
 62         cell.setCellValue("检查项"); 
 63         cell.setCellStyle(cellStyle);
 64         sheet.setColumnWidth(2, 5000);
 65         cell = row.createCell((short) 3);
 66         cell.setCellValue("检查次数");
 67         cell.setCellStyle(cellStyle);
 68         sheet.setColumnWidth(3, 5000);
 69         cell = row.createCell((short) 4);
 70         cell.setCellValue("检查时间");
 71         cell.setCellStyle(cellStyle);
 72         sheet.setColumnWidth(4, 5000);
 73         cell = row.createCell((short) 5);
 74         cell.setCellValue("记录更新时间");
 75         cell.setCellStyle(cellStyle);
 76         sheet.setColumnWidth(5, 5000);        
 77         cell = row.createCell((short) 6);        
 78         cell.setCellValue("当前状态");
 79         cell.setCellStyle(cellStyle);
 80         sheet.setColumnWidth(6, 4000);
 81         cell = row.createCell((short) 7);
 82         cell.setCellValue("异常等级");
 83         cell.setCellStyle(cellStyle);
 84         sheet.setColumnWidth(7, 4000);
 85         cell = row.createCell((short) 8);
 86         
 87         wb.setSheetName(0, sheetName);        
 88         if(sheetResult.size() == 0){
 89             XSSFRow rows=sheet.createRow(1);
 90             rows.setHeight((short) 500);
 91             rows.createCell(0).setCellValue("没有查询结果!");
 92             return wb;
 93         }
 94         
 95         for(int info = 0; info < sheetResult.size(); info ++){
 96             XSSFRow rows=sheet.createRow(info+1);
 97             rows.setHeight((short) 500);
 98             Map<String,Object> map = sheetResult.get(info);
 99             
100             rows.createCell(0).setCellValue(map.get("name") + "");
101             rows.createCell(1).setCellValue(map.get("ac_mac") + "");
102             rows.createCell(2).setCellValue(map.get("item_code") + "");            
103             rows.createCell(3).setCellValue(map.get("check_times") + "");
104             rows.createCell(4).setCellValue(map.get("check_time") + "");
105             rows.createCell(5).setCellValue(map.get("update_time") + "");
106             rows.createCell(6).setCellValue(map.get("status") + "");
107             rows.createCell(7).setCellValue(map.get("exception_level") + "");               
108             //多插一行,避免单元格溢出
109             rows.createCell(8).setCellValue(" ");
110         }
111         
112         return wb;
113     }