使用apache的poi实现导入导出excel
1、jar包:poi-3.14-20160307.jar、poi-ooxml-3.14-20160307.jar
2、导入(本例实现了解析excel生成List):
@Override
public Map<String, Object> parseExcel(String fileName) { // 1.准备返回的变量
Map<String, Object> resultMap = new HashMap<String, Object>();
String message = "success";
List<Stone> stones = new ArrayList<Stone>(); boolean isE2007 = false; // 判断是否是excel2007格式
if (fileName.endsWith("xlsx")) {
isE2007 = true;
}
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); // 2.准备workbook
// 同时支持Excel 2003、2007
File excelFile = new File(fileName); // 创建文件对象
Workbook workbook = null;
// 根据文件格式(2003或者2007)来初始化
try {
FileInputStream is = new FileInputStream(excelFile); // 文件流
if (isE2007) {
workbook = new XSSFWorkbook(is);
} else {
workbook = new HSSFWorkbook(is);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} // 3.遍历集合,组装结果
int sheetCount = workbook.getNumberOfSheets(); // Sheet的数量
// 遍历每个Sheet
for (int s = 0; s < sheetCount; s++) {
Sheet sheet = workbook.getSheetAt(s);
int rowCount = sheet.getPhysicalNumberOfRows(); // 获取总行数
// 遍历每一行
for (int r = 1; r < rowCount; r++) {
Stone stone = new Stone();
Row row = sheet.getRow(r);
int cellCount = row.getPhysicalNumberOfCells(); // 获取总列数
// 遍历每一列
for (int c = 0; c < cellCount; c++) {
Cell cell = row.getCell(c);
int cellType = cell.getCellType();
String cellStringValue = null;
switch (cellType) {
case Cell.CELL_TYPE_STRING: // 文本
cellStringValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC: // 数字、日期
if (DateUtil.isCellDateFormatted(cell)) {
cellStringValue = fmt.format(cell.getDateCellValue()); // 日期型
} else {
cellStringValue = String.valueOf(cell.getNumericCellValue()); // 数字
if (cellStringValue.contains("E")) {
cellStringValue = String.valueOf(new Double(cell.getNumericCellValue()).longValue()); // 数字
}
}
break;
case Cell.CELL_TYPE_BOOLEAN: // 布尔型
cellStringValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_BLANK: // 空白
cellStringValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_ERROR: // 错误
cellStringValue = "错误";
break;
case Cell.CELL_TYPE_FORMULA: // 公式
cellStringValue = "错误";
break;
default:
cellStringValue = "错误";
} if (cellStringValue.equals("错误")) {
message = "解析Excel时发生错误,第[" + (s + 1) + "]sheet,第[" + (row.getRowNum() + 1) + "]行,第[" + (c + 1)
+ "]列解析错误";
resultMap.put("message", message);
return resultMap;
} cellStringValue = cellStringValue.trim(); switch (c) {
case ConstantsUtil.STONE_EXCEL_COLUMN_STONEID:
try {
new Long(cellStringValue);
} catch (NumberFormatException e) {
message = "解析Excel时发生错误,第[" + (s + 1) + "]sheet,第[" + (row.getRowNum() + 1) + "]行,第["
+ (c + 1) + "]列值类型转换异常";
resultMap.put("message", message);
return resultMap;
}
stone.setStoneId(new Long(cellStringValue));
break;
case ConstantsUtil.STONE_EXCEL_COLUMN_SHAPE:
stone.setShape(cellStringValue);
break;
case ConstantsUtil.STONE_EXCEL_COLUMN_CARAT:
try {
new Double(cellStringValue);
} catch (NumberFormatException e) {
message = "解析Excel时发生错误,第[" + (s + 1) + "]sheet,第[" + (row.getRowNum() + 1) + "]行,第["
+ (c + 1) + "]列值类型转换异常";
resultMap.put("message", message);
return resultMap;
}
stone.setCarat(new Double(cellStringValue));
break;
case ConstantsUtil.STONE_EXCEL_COLUMN_COLOUR:
stone.setColour(cellStringValue);
break;
case ConstantsUtil.STONE_EXCEL_COLUMN_CLARITY:
stone.setClarity(cellStringValue);
break;
case ConstantsUtil.STONE_EXCEL_COLUMN_CUT:
stone.setCut(cellStringValue);
break;
case ConstantsUtil.STONE_EXCEL_COLUMN_POLISH:
stone.setPolish(cellStringValue);
break;
case ConstantsUtil.STONE_EXCEL_COLUMN_SYM:
stone.setSym(cellStringValue);
break;
case ConstantsUtil.STONE_EXCEL_COLUMN_FLUOR:
stone.setFluor(cellStringValue);
break;
case ConstantsUtil.STONE_EXCEL_COLUMN_DIAMETER:
try {
new Double(cellStringValue);
} catch (NumberFormatException e) {
message = "解析Excel时发生错误,第[" + (s + 1) + "]sheet,第[" + (row.getRowNum() + 1) + "]行,第["
+ (c + 1) + "]列值类型转换异常";
resultMap.put("message", message);
return resultMap;
}
stone.setDiameter(new Double(cellStringValue));
break;
case ConstantsUtil.STONE_EXCEL_COLUMN_PLENGTH:
try {
new Double(cellStringValue);
} catch (NumberFormatException e) {
message = "解析Excel时发生错误,第[" + (s + 1) + "]sheet,第[" + (row.getRowNum() + 1) + "]行,第["
+ (c + 1) + "]列值类型转换异常";
resultMap.put("message", message);
return resultMap;
}
stone.setpLength(new Double(cellStringValue));
break;
case ConstantsUtil.STONE_EXCEL_COLUMN_PWEIGHT:
try {
new Double(cellStringValue);
} catch (NumberFormatException e) {
message = "解析Excel时发生错误,第[" + (s + 1) + "]sheet,第[" + (row.getRowNum() + 1) + "]行,第["
+ (c + 1) + "]列值类型转换异常";
resultMap.put("message", message);
return resultMap;
}
stone.setpWeight(new Double(cellStringValue));
break;
case ConstantsUtil.STONE_EXCEL_COLUMN_PDEPTH:
try {
new Double(cellStringValue);
} catch (NumberFormatException e) {
message = "解析Excel时发生错误,第[" + (s + 1) + "]sheet,第[" + (row.getRowNum() + 1) + "]行,第["
+ (c + 1) + "]列值类型转换异常";
resultMap.put("message", message);
return resultMap;
}
stone.setpDepth(new Double(cellStringValue));
break;
case ConstantsUtil.STONE_EXCEL_COLUMN_PDEPTHPER:
try {
new Double(cellStringValue);
} catch (NumberFormatException e) {
message = "解析Excel时发生错误,第[" + (s + 1) + "]sheet,第[" + (row.getRowNum() + 1) + "]行,第["
+ (c + 1) + "]列值类型转换异常";
resultMap.put("message", message);
return resultMap;
}
stone.setpDepthPer(new Double(cellStringValue));
break;
case ConstantsUtil.STONE_EXCEL_COLUMN_PTABLE:
try {
new Double(cellStringValue);
} catch (NumberFormatException e) {
message = "解析Excel时发生错误,第[" + (s + 1) + "]sheet,第[" + (row.getRowNum() + 1) + "]行,第["
+ (c + 1) + "]列值类型转换异常";
resultMap.put("message", message);
return resultMap;
}
stone.setpTable(new Double(cellStringValue));
break;
case ConstantsUtil.STONE_EXCEL_COLUMN_LAB:
stone.setLab(cellStringValue);
break;
case ConstantsUtil.STONE_EXCEL_COLUMN_CERTIID:
stone.setCertiId(cellStringValue);
break;
case ConstantsUtil.STONE_EXCEL_COLUMN_STOCKIN:
Integer stockIn = 0;
if ("是".equals(cellStringValue)) {
stockIn = 1;
}
stone.setStockIn(stockIn);
break;
case ConstantsUtil.STONE_EXCEL_COLUMN_STOCKCITY:
stone.setStockCity(cellStringValue);
break;
case ConstantsUtil.STONE_EXCEL_COLUMN_SINGLEPRICE:
try {
new BigDecimal(cellStringValue);
} catch (NumberFormatException e) {
message = "解析Excel时发生错误,第[" + (s + 1) + "]sheet,第[" + (row.getRowNum() + 1) + "]行,第["
+ (c + 1) + "]列值类型转换异常";
resultMap.put("message", message);
return resultMap;
}
stone.setSinglePrice(new BigDecimal(cellStringValue));
break;
default:
message = "解析Excel时发生错误,第[" + (row.getRowNum() + 1) + "]行,第[" + (c + 1) + "]列不应该有值";
resultMap.put("message", message);
return resultMap;
}
}
stone.setIsOnSale(false);
stone.setIsDelete(false);
stones.add(stone);
}
}
resultMap.put("message", message);
resultMap.put("stones", stones);
return resultMap;
}
3、导出
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor; import com.alibaba.fastjson.JSON; class DataInfo {
private String countDate; // 统计日期
private String channelId; // 渠道号 public String getCountDate() {
return countDate;
} public void setCountDate(String countDate) {
this.countDate = countDate;
} public String getChannelId() {
return channelId;
} public void setChannelId(String channelId) {
this.channelId = channelId;
}
};
public class TestExport {
public static void main(String[] args) throws IOException {
// 创建
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
// 创建单元格样式
HSSFCellStyle titleCellStyle = wb.createCellStyle();
// 指定单元格居中对齐,边框为细
titleCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
titleCellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
titleCellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
titleCellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
titleCellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
titleCellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
// 设置填充色
titleCellStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
titleCellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
// 指定当单元格内容显示不下时自动换行
titleCellStyle.setWrapText(true);
// 设置单元格字体
HSSFFont titleFont = wb.createFont();
titleFont.setFontHeightInPoints((short) 12);
titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
titleCellStyle.setFont(titleFont);
HSSFRow headerRow = sheet.createRow(0);
HSSFCell headerCell = null;
String[] titles = { "统计日期", "渠道号" };
for (int c = 0; c < titles.length; c++) {
headerCell = headerRow.createCell(c);
headerCell.setCellStyle(titleCellStyle);
headerCell.setCellValue(titles[c]);
sheet.setColumnWidth(c, (30 * 160));
}
// ------------------------------------------------------------------
// 创建单元格样式
HSSFCellStyle cellStyle = wb.createCellStyle();
// 指定单元格居中对齐,边框为细
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
// 设置单元格字体
HSSFFont font = wb.createFont();
titleFont.setFontHeightInPoints((short) 11);
font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
cellStyle.setFont(font);
String infoStr = "[{\"channelId\":\"bodao\",\"countDate\":\"2014-06-11\"},"
+ "{\"channelId\":\"dingzhi\",\"countDate\":\"2014-06-12\"},"
+ "{\"channelId\":\"ruiwei\",\"countDate\":\"2014-06-13\"}]";
List<DataInfo> list = JSON.parseArray(infoStr, DataInfo.class);
for (int r = 0; r < list.size(); r++) {
DataInfo item = list.get(r);
HSSFRow row = sheet.createRow(r + 1);
HSSFCell cell = null;
int c = 0;
cell = row.createCell(c++);
cell.setCellStyle(cellStyle);
cell.setCellValue(item.getCountDate());
cell = row.createCell(c++);
cell.setCellStyle(cellStyle);
cell.setCellValue(item.getChannelId());
} FileOutputStream fileOut = new FileOutputStream("E:/test/test.xls");
wb.write(fileOut);
fileOut.close();
System.out.println("Done");
}
}
爱的反复
使用apache的poi实现导入导出excel的更多相关文章
- Java利用POI实现导入导出Excel表格示例代码
转自:https://www.jb51.net/article/95526.htm 介绍 Jakarta POI 是一套用于访问微软格式文档的Java API.Jakarta POI有很多组件组成,其 ...
- Java利用POI导入导出Excel中的数据
首先谈一下今天发生的一件开心的事,本着一颗android的心我被分配到了PB组,身在曹营心在汉啊!好吧,今天要记录和分享的是Java利用POI导入导出Excel中的数据.下面POI包的下载地 ...
- apache poi根据模板导出excel
需要预先新建编辑好一个excel文件,设置好样式. 编辑好输出的数据,根据excel坐标一一对应. 支持列表数据输出,列表中列合并. 代码如下: package com.icourt.util; im ...
- Java使用POI实现数据导出excel报表
Java使用POI实现数据导出excel报表 在上篇文章中,我们简单介绍了java读取word,excel和pdf文档内容 ,但在实际开发中,我们用到最多的是把数据库中数据导出excel报表形式.不仅 ...
- 导入导出Excel文件
搭建环境 先新建web project ,然后Add Struts Capabilties: 下载导入导出Excel所需的jar包: poi-3.8-20120326.jar包 : http:// ...
- Java基于注解和反射导入导出Excel
代码地址如下:http://www.demodashi.com/demo/11995.html 1. 构建项目 使用Spring Boot快速构建一个Web工程,并导入与操作Excel相关的POI包以 ...
- EasyPOI导入导出Excel
EasyPOI工具可以方便的写出Excel导出,Excel模板导出,Excel导入,Word模板导出,通过简单的注解和模板 导入maven依赖 <dependency> <group ...
- java使用户EasyExcel导入导出excel
使用alibab的EasyExce完成导入导出excel 一.准备工作 1.导包 <!-- poi 相关--> <dependency> <groupId>org. ...
- 导入导出Excel工具类ExcelUtil
前言 前段时间做的分布式集成平台项目中,许多模块都用到了导入导出Excel的功能,于是决定封装一个ExcelUtil类,专门用来处理Excel的导入和导出 本项目的持久化层用的是JPA(底层用hibe ...
随机推荐
- C# 执行bat批处理文件
private void RunBat(string batPath) { Process pro = new Process(); FileInfo file = new FileInfo(batP ...
- hive INSERT OVERWRITE table could not be cleaned up.
create table maats.account_channel ROW FORMAT DELIMITED FIELDS TERMINATED BY '^' STORED AS TEXTFILE ...
- iOS内存管理和优化 from 刘延军
- 【微信小程序】使用setTimeout制作定时器的思路
setTimeout(func, time)可以使得每隔time毫秒就执行一次func函数,常用来做计时器/时钟. 下面是在微信小程序中的使用思路,只截取了关键部分代码. var timer; // ...
- Android——Service
xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android= ...
- Redis列表
Redis列表是简单的字符串列表,排序插入顺序.您可以在头部或列表的尾部Redis的列表添加元素. 列表的最大长度为232 – 1 (每个列表超过4十亿元素4294967295)元素. 例子 redi ...
- kindle书摘-活着-余华-活着不易,珍惜
https://github.com/starrtc/android-demo 中文版自序 标注(黄色) - 位置 29 作家的使命不是发泄,不是控诉或者揭露,他应该向人们展示高尚.这里所说的高尚不 ...
- Qt中QString::toStdString().c_str() 偶尔存在问题
假设 QString str = "string"; const char* c = str.toStdString().c_str()单步调试显示的结果可能会是'\0' 而当我这 ...
- 取消excel 工作保护 密码的宏
Option Explicit Public Sub AllInternalPasswords() ' Breaks worksheet and workbook structure password ...
- Unity入门教程(上)
一.介绍 目的:通过尝试制作一款使用玩家角色把小球弹飞的简单小游戏,熟悉使用Unity进行游戏开发的基本流程. 软件环境:Unity 2017.3.0f3,Visual Studio 2013 二.创 ...