<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
</dependencies>
import java.io.*;
import java.util.*;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelUtil { public static List<List<String>> readExcel(String filePath) {
List<List<String>> dataLst = null;
InputStream is = null;
try {
//验证文件是否合法
if (!validateExcel(filePath)) {
return null;
}
// 判断文件的类型,是2003还是2007
boolean isExcel2003 = true;
if (isExcel2007(filePath)) {
isExcel2003 = false;
}
// 调用本类提供的根据流读取的方法
File file = new File(filePath);
is = new FileInputStream(file);
dataLst = read(is, isExcel2003); } catch (Exception ex) {
ex.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
is = null;
e.printStackTrace();
}
}
} return dataLst;
} private static List<List<String>> read(InputStream inputStream, boolean isExcel2003) {
List<List<String>> dataLst = null;
try {
//根据版本选择创建Workbook的方式
Workbook wb = null;
if (isExcel2003) {
wb = new HSSFWorkbook(inputStream);
} else {
wb = new XSSFWorkbook(inputStream);
}
dataLst = read(wb);
} catch (IOException e) {
e.printStackTrace();
}
return dataLst;
} private static List<List<String>> read(Workbook wb) {
int totalRows = ;
int totalCells = ;
List<List<String>> dataLst = new ArrayList<List<String>>();
// 得到第一个shell
Sheet sheet = wb.getSheetAt();
// 得到Excel的行数
totalRows = sheet.getPhysicalNumberOfRows();
// 得到Excel的列数
if (totalRows >= && sheet.getRow() != null) {
totalCells = sheet.getRow().getPhysicalNumberOfCells();
}
//遍历行
for (int r = ; r < totalRows; r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
List<String> rowLst = new ArrayList<String>();
//遍历列
for (int c = ; c < totalCells; c++) {
Cell cell = row.getCell(c);
String cellValue = "";
if (null != cell) {
// 以下是判断数据的类型
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC: // 数字
cellValue = cell.getNumericCellValue() + "";
break;
case HSSFCell.CELL_TYPE_STRING: // 字符串
cellValue = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
cellValue = cell.getBooleanCellValue() + "";
break;
case HSSFCell.CELL_TYPE_FORMULA: // 公式
cellValue = cell.getCellFormula() + "";
break;
case HSSFCell.CELL_TYPE_BLANK: // 空值
cellValue = "";
break;
case HSSFCell.CELL_TYPE_ERROR: // 故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
}
rowLst.add(cellValue);
}
// 保存第r行的第c列
dataLst.add(rowLst);
}
return dataLst;
} private static boolean validateExcel(String filePath) {
// 检查文件名是否为空或者是否是Excel格式的文件
if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
return false;
}
// 检查文件是否存在
File file = new File(filePath);
if (file == null || !file.exists()) {
return false;
}
return true;
} private static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
} private static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
} public static void writeExcel(List<List<String>> dataList, String finalXlsxPath){
OutputStream out = null;
try { // 读取Excel文档
File finalXlsxFile = new File(finalXlsxPath);
Workbook workBook = getWorkbok(finalXlsxFile);
// sheet 对应一个工作页
Sheet sheet = workBook.getSheetAt(); //删除原有数据,除了属性列
int rowNumber = sheet.getLastRowNum();
for (int i = ; i <= rowNumber; i++) {
Row row = sheet.getRow(i);
sheet.removeRow(row);
} // 创建文件输出流,输出电子表格:这个必须有,否则你在sheet上做的任何操作都不会有效
out = new FileOutputStream(finalXlsxPath);
workBook.write(out); //写一行
for (int j = ; j < dataList.size(); j++) {
Row row = sheet.createRow(j); //写一列
List<String> datas = dataList.get(j);
for (int k=; k<datas.size(); k++) {
row.createCell(k).setCellValue(datas.get(k));
}
} // 创建文件输出流,准备输出电子表格:这个必须有,否则你在sheet上做的任何操作都不会有效
out = new FileOutputStream(finalXlsxPath);
workBook.write(out);
System.out.println("数据导出成功");
} catch (Exception e) {
System.out.println("请创建一个空文件");
e.printStackTrace();
} finally{
try {
if(out != null){
out.flush();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} } private static final String EXCEL_XLS = "xls";
private static final String EXCEL_XLSX = "xlsx"; private static Workbook getWorkbok(File file) throws IOException{
Workbook wb = null;
FileInputStream in = new FileInputStream(file);
if(file.getName().endsWith(EXCEL_XLS)){ //Excel&nbsp;2003
wb = new HSSFWorkbook(in);
}else if(file.getName().endsWith(EXCEL_XLSX)){ // Excel 2007/2010
wb = new XSSFWorkbook(in);
}
return wb;
} }
import java.util.ArrayList;
import java.util.List; public class Test { public static void main(String[] args) {
List<List<String>> resultList = ExcelUtil.readExcel("H:/data.xlsx");
if (resultList != null) {
for (int i = ; i < resultList.size(); i++) {
System.out.print("第" + (i) + "行");
List<String> cellList = resultList.get(i); for (int j = ; j < cellList.size(); j++) {
System.out.print(" " + cellList.get(j));
}
System.out.println();
} } //把读取的结果在写回去
ExcelUtil.writeExcel(resultList, "H:/result.xlsx");
}
}

Java读写Excel的更多相关文章

  1. C++读写EXCEL文件OLE,java读写excel文件POI 对比

    C++读写EXCEL文件方式比较 有些朋友问代码的问题,将OLE读写的代码分享在这个地方,大家请自己看.http://www.cnblogs.com/destim/p/5476915.html C++ ...

  2. Java读写Excel之POI超入门

    转自:http://rensanning.iteye.com/blog/1538591 Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给J ...

  3. Java读写Excel之POI超入门(转)

    Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office格式档案读和写的功能.Apache POI ...

  4. Java 读写 excel 实战完全解析

    本文微信公众号「AndroidTraveler」首发. 背景 时值毕业季,很多毕业生初入职场. 因此,这边也写了一些新手相关的 Android 技术点. 比如上一篇的 Android 开发你需要了解的 ...

  5. java读写excel文件

    近期处理的数据规模比较大,正好又是统计合并的事情,想着借助excel就可以完成了,然后就了解了下java读取excel的事情. 读取的文件主要分两类:xls文件.xlsx文件.xls文件的相关操作用的 ...

  6. 利用java读写Excel文件

    一.读取Excel文件内容 java 代码 public static String readExcel(File file){ StringBuffer sb = new StringBuffer( ...

  7. java读写excel文件( POI解析Excel)

    package com.zhx.base.utils; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi ...

  8. JAVA 读写Excel

    ExcelUtil.java package pers.kangxu.datautils.utils; import java.io.File; import java.io.FileInputStr ...

  9. Java读写Excel文件,利用POI

    直接看工具类代码吧, package com.example.demo.util; import com.example.demo.entity.ExcelDataVO; import org.apa ...

随机推荐

  1. firewall 防火墙相关

    修改配置文件: /etc/sysconfig/network-scripts/ifcfg-ens33 文件 ONBOOT=no 改为yes 然后重启  service network restart ...

  2. ABP官方文档翻译 1.4 启动配置

    启动配置 配置ABP 替换内置服务 配置模块 创建模块配置 ABP提供了基础设施和模型在启动的时候对它及模块进行配置. 配置ABP 在模块的PreInitialize事件中配置ABP.示例配置如下: ...

  3. HashMap,HashTable,ConcorrentHashMap的线程方式

    1.HashMap不是线程安全的,put,resize 2.HashTable是线程安全的,synchronized,但是效率较低 3.ConcorrentHashMap 对HashMap的一种加线程 ...

  4. Spring Security核心概念介绍

    Spring Security是一个强大的java应用安全管理库,特别适合用作后台管理系统.这个库涉及的模块和概念有一定的复杂度,而大家平时学习Spring的时候也不会涉及:这里基于官方的参考文档,把 ...

  5. STC51几种简单的延时函数

    STC51几种简单的延时函数 ,* 延时子程序 * * * ********************************************************************** ...

  6. SaltStack安装Redis-第十篇

    实验环境 node1  192.168.56.11   角色  salt-master node2  192.168.56.12   角色  salt-minon 完成内容 Salt远程安装Redis ...

  7. 1568: [JSOI2008]Blue Mary开公司

    1568: [JSOI2008]Blue Mary开公司 题目描述 传送门 题目分析 简单分析可以发现就是不停给出了\(n\)条直线,要求每次给出一条直线后求出所有直线在横坐标为\(x\)时\(y\) ...

  8. 在Linux Centos 7.2 上安装指定版本Docker。

    相关资料链接: https://docs.docker.com/install/linux/docker-ce/centos/#install-docker-ce 先清空下“历史” yum remov ...

  9. Vjudge - F - 比前面更简单的模拟

    2017-07-16 07:31:35 writer:pprp 题目介绍:很基础的string用法 题目如下: 读入一个字符串,字符串中包含ZOJ三个字符,个数不一定相等,按ZOJ的顺序输出,当某个字 ...

  10. HDU5324 cqd分治

    HDU5324 cqd分治 标签(空格分隔): 未分类 给你两个长度相同数列,求第一个不上升,第二个不下降的最长子序列长度. 这里要求的子序列对第一个和第二个来说是相同的.即如果你在第一个序列里选了第 ...