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

一、读EXCEL文件

 package com.ruijie.wis.cloud.utils;

 import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class ProjectImportUtil {
public ProjectImportUtil() {
String fileName = "D:\tst.xlsx";
  InputStream input = new FileInputStream(fileName);     
} /* 导入销售数据 ,excel2007格式 */
public List<Map<String,Object>> importSaleXml(InputStream input, String industry) {
List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
DecimalFormat df =new DecimalFormat("#0"); try {
XSSFWorkbook wb = new XSSFWorkbook(input); // Excel 2003 使用wb = new HSSFWorkbook(input); FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
 int index_name = 0;
int index_province = 0;
int index_city = 0;
int index_acs = 0;
int index_aps = 0;
int index_zuozhi = 0;
String industry_name = industry;
XSSFSheet sheet = wb.getSheet(industry_name);
if(sheet == null) {
logger.warn("importSaleXml - industy: " + industry_name + " not exist!");
wb.close();
return null;
}
Iterator<Row> rows = sheet.rowIterator(); while (rows.hasNext()) {
  Row row = rows.next();
  if(row.getRowNum() == 0) { // 查找关心的数据所在列号
  Iterator<Cell> cells = row.cellIterator();
  while (cells.hasNext()) {
    Cell cell = cells.next();
    String title = getCellValue(cell,evaluator);
    if(title.equals("最终客户名称")) {
      index_name = cell.getColumnIndex();
    } else if(title.equals("省份")) {
      index_province = cell.getColumnIndex();
    } else if(title.equals("城市")) {
      index_city = cell.getColumnIndex();
    } else if(title.equals("AC系列")) {
      index_acs = cell.getColumnIndex();
    } else if(title.equals("AP系列")) {
      index_aps = cell.getColumnIndex();
    } else if(title.equals("卓智客户名称")) {
      index_zuozhi = cell.getColumnIndex();
  }
  }
}   Cell cell_name = row.getCell(index_name);
  Cell cell_province = row.getCell(index_province);
  Cell cell_city = row.getCell(index_city);
  Cell cell_acs = row.getCell(index_acs);
  Cell cell_aps = row.getCell(index_aps);
  String projectName = getCellValue(cell_name,evaluator);
  String province = getCellValue(cell_province,evaluator);
  String city = getCellValue(cell_city,evaluator);
  String acs = getCellValue(cell_acs,evaluator);
  String aps = getCellValue(cell_aps,evaluator);   Map<String,Object> salevalue = new HashMap<String, Object>();
  salevalue.put("projectName", projectName);
  salevalue.put("industry_name", industry_name);
  if(province != null) {  
    salevalue.put("province", province);
  }
  if(city != null) {
    salevalue.put("city", city);
  }
  if(acs != null) {  
    salevalue.put("acs", acs);
  }
  if(aps != null) {
    salevalue.put("aps", aps);   }   result.add(salevalue);
}
  wb.close();
} catch (Exception e) {
  logger.error(e.toString(),e);
}
  return result;
} //根据cell中的类型来返回数据
public String getCellValue(Cell cell, FormulaEvaluator evaluator) {
  if(cell == null) {
    return null;
  }
  CellValue cellValue = evaluator.evaluate(cell);
  if(cellValue == null) {
    return null;
  }
  switch (cellValue.getCellType()) {
  case HSSFCell.CELL_TYPE_NUMERIC:
  return cell.getNumericCellValue() + "";
  case HSSFCell.CELL_TYPE_STRING:
  return cell.getStringCellValue() + "";
  case HSSFCell.CELL_TYPE_BOOLEAN:
  return cell.getBooleanCellValue() + "";
  case HSSFCell.CELL_TYPE_FORMULA:
  return cell.getCellFormula();
  default:
  return null;
}
} }

二、写EXCEL文件

 XSSFWorkbook wb=new XSSFWorkbook();
DeviceAlarmUtil outputResult = new DeviceAlarmUtil();
wb = outputResult.outConfigExceptionResult(wb, "配置告警信息", configAlarmList);
response.setContentType("application/msexcel");
response.setHeader( "Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1" ) ); ServletOutputStream os = null;
try {
os = response.getOutputStream();
//写到输出流
wb.write(os);
12 } catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Throwable e) {
e.printStackTrace();
} finally {
if (wb != null) {
try {
wb.close();
} catch (IOException e) {
throw new Exception("IO错误,无法导出结果");
}
}
if (os != null) {
try {
  os.flush();
os.close();
} catch (IOException e) {
throw new Exception("IO错误,无法导出结果");
}
}
} public XSSFWorkbook outConfigExceptionResult(XSSFWorkbook wb, String sheetName, List<Map<String, Object>> sheetResult){
XSSFSheet sheet=wb.createSheet(sheetName);
XSSFRow row=sheet.createRow(0);
CellStyle cellStyle =wb.createCellStyle();
// 设置这些样式
cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
cellStyle.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
XSSFFont font = wb.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
cellStyle.setFont(font); XSSFCell cell = row.createCell((short) 0);
cell.setCellValue("客户名称");
cell.setCellStyle(cellStyle);
sheet.setColumnWidth(0, 5500);
cell = row.createCell((short) 1);
cell.setCellValue("AC MAC");
cell.setCellStyle(cellStyle);
sheet.setColumnWidth(1, 5000);
cell = row.createCell((short) 2);
cell.setCellValue("检查项");
cell.setCellStyle(cellStyle);
sheet.setColumnWidth(2, 5000);
cell = row.createCell((short) 3);
cell.setCellValue("检查次数");
cell.setCellStyle(cellStyle);
sheet.setColumnWidth(3, 5000);
cell = row.createCell((short) 4);
cell.setCellValue("检查时间");
cell.setCellStyle(cellStyle);
sheet.setColumnWidth(4, 5000);
cell = row.createCell((short) 5);
cell.setCellValue("记录更新时间");
cell.setCellStyle(cellStyle);
sheet.setColumnWidth(5, 5000);
cell = row.createCell((short) 6);
cell.setCellValue("当前状态");
cell.setCellStyle(cellStyle);
sheet.setColumnWidth(6, 4000);
cell = row.createCell((short) 7);
cell.setCellValue("异常等级");
cell.setCellStyle(cellStyle);
sheet.setColumnWidth(7, 4000);
cell = row.createCell((short) 8); wb.setSheetName(0, sheetName);
if(sheetResult.size() == 0){
XSSFRow rows=sheet.createRow(1);
rows.setHeight((short) 500);
rows.createCell(0).setCellValue("没有查询结果!");
return wb;
} for(int info = 0; info < sheetResult.size(); info ++){
XSSFRow rows=sheet.createRow(info+1);
rows.setHeight((short) 500);
Map<String,Object> map = sheetResult.get(info); rows.createCell(0).setCellValue(map.get("name") + "");
rows.createCell(1).setCellValue(map.get("ac_mac") + "");
rows.createCell(2).setCellValue(map.get("item_code") + "");
rows.createCell(3).setCellValue(map.get("check_times") + "");
rows.createCell(4).setCellValue(map.get("check_time") + "");
rows.createCell(5).setCellValue(map.get("update_time") + "");
rows.createCell(6).setCellValue(map.get("status") + "");
rows.createCell(7).setCellValue(map.get("exception_level") + "");
//多插一行,避免单元格溢出
rows.createCell(8).setCellValue(" ");
} return wb;
}
上一篇:Java使用POI读取和写入Excel指南


下一篇:blog搬迁