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使用org.apache.poi读取与保存EXCEL文件的更多相关文章
- 【Java】使用Apache POI生成和解析Excel文件
概述 Excel是我们平时工作中比较常用的用于存储二维表数据的,JAVA也可以直接对Excel进行操作,分别有jxl和poi,2种方式. HSSF is the POI Project's pure ...
- Java中使用POI读取大的Excel文件或者输入流时发生out of memory异常参考解决方案
注意:此参考解决方案只是针对xlsx格式的excel文件! 背景 前一段时间遇到一种情况,服务器经常宕机,而且没有规律性,查看GC日志发生了out of memory,是堆溢出导致的,分析了一下堆的d ...
- Java 使用Apache POI读取和写入Excel表格
1,引入所用的包 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxm ...
- Java开发小技巧(六):使用Apache POI读取Excel
前言 在数据仓库中,ETL最基础的步骤就是从数据源抽取所需的数据,这里所说的数据源并非仅仅是指数据库,还包括excel.csv.xml等各种类型的数据接口文件,而这些文件中的数据不一定是结构化存储的, ...
- Java使用POI读取和写入Excel指南
Java使用POI读取和写入Excel指南 做项目时经常有通过程序读取Excel数据,或是创建新的Excel并写入数据的需求: 网上很多经验教程里使用的POI版本都比较老了,一些API在新版里已经废弃 ...
- 项目一:第四天 1、快递员的条件分页查询-noSession,条件查询 2、快递员删除(逻辑删除) 3、基于Apache POI实现批量导入区域数据 a)Jquery OCUpload上传文件插件使用 b)Apache POI读取excel文件数据
1. 快递员的条件分页查询-noSession,条件查询 2. 快递员删除(逻辑删除) 3. 基于Apache POI实现批量导入区域数据 a) Jquery OCUpload上传文件插件使用 b) ...
- 用 Apache POI 读取 XLSX 数据
最近因为项目的原因,需要从一些 Microsoft Office Excel 文件读取数据并加载到数据库. Google了一下方法,发现其实可以用的 Java 第三方库很多,最著名的是 Apache ...
- java使用poi读取doc和docx文件(maven自动导入依赖包)
java使用poi读取doc和docx文件(maven自动导入依赖包) 于是在网上搜寻了一阵之后才发现原来doc文档和excel一样不能用普通的io流的方法来读取,而是也需要用poi,于是进行了一番尝 ...
- Apache POI – Reading and Writing Excel file in Java
来源于:https://www.mkyong.com/java/apache-poi-reading-and-writing-excel-file-in-java/ In this article, ...
随机推荐
- 【英语】Bingo口语笔记(80) - 记忆、忘记的表达
- HttpWebRequest模拟c#网站登录
用户名 密码 模拟登录asp.net开发的网站 关心两个问题:通过控件属性获取数据.响应事件. 上面是一个普通的asp.net表单.输入用户名.密码后,点击按钮将会进入各自绑定的后台函数,而不仅仅是 ...
- 【解题报告】POJ-1108 Split Windows
原题地址:http://poj.org/problem?id=1108 ============================== 题目大意: 一棵树表示一个窗口,它的叶子节点都是大写字母,非叶子节 ...
- 【转】关于Python脚本开头两行的:#!/usr/bin/python和# -*- coding: utf-8 -*-的作用 – 指定文件编码类型
原文网址:http://www.crifan.com/python_head_meaning_for_usr_bin_python_coding_utf-8/ #!/usr/bin/python 是用 ...
- 不可或缺的 sendEmail
还在为Linux下没有便捷的邮件程序苦恼,还在为复杂的邮件服务器架设Google N多网页? 对于小型,便捷的Linux下命令行邮件程序,sendEmail使得这一切变得轻松可行.一起来看看吧. 一. ...
- php5.2转向 PHP 5.3 的 PHP 开发
PHP 5.3 开始,为了更好的向 PHP 的未来版本(PHP6) 过渡,将未来不再支持的函数标记为 DEPRECATED.在代码中使用这些函数,将毫不留情的在页面中显示警告信息:“使用了过时的函数… ...
- 使用 XML 实现 REST 式的 SOA
什么是 SOA? 如果公司有大量应用程序,这些程序供不同部门的承担不同责任的职员使用,那么就适合使用面向服务体系结构(Service Oriented Architecture,SOA).这些应用程序 ...
- 职业操盘手内部教材 z
重 点抢筹区: 是主力机构在低位拉高建仓后的一个相当尴尬的区域!因为在这个区域,场外的绝大多数投资者不敢买,而场内持有的人却很想卖!所以会出现成片的卖盘挂单! 由于主力向上做的意图已经非常明显,所 ...
- Delphi 异或,英文为exclusive OR,或缩写成xor
异或,英文为exclusive OR,或缩写成xor 异或(xor)是一个数学运算符.它应用于逻辑运算.异或的数学符号为“⊕”,计算机符号为“xor”.其运算法则为: a⊕b = (¬a ∧ b) ∨ ...
- windows10UWP开发真机调试时遇到DEP6100和DEP6200解决办法
windows10UWP开发真机调试时遇到DEP6100和DEP6200(其实未连接上设备都会报这两个错误,无论真机还是虚拟机)…… 此方法适合真机调试时遇到: 弹出提示框要求输入配对码,无论如何输入 ...