一、jar包

二、工具类

package excel;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List; 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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class XLSOprUtil {
private static final Logger logger = LoggerFactory.getLogger(XLSOprUtil.class); public static void main(String[] args) throws Exception {
final String filename = "userInfo.xlsx";
new XLSOprUtil(filename).readExcel(0);
} private InputStream inp;
private String filePath; public XLSOprUtil(String filePath) throws FileNotFoundException {
this.inp = new FileInputStream(filePath);
this.filePath = filePath;
} /**
* 读取xls文件内容
*
* @param isCloseStream
* true:读取内容完成后,关闭流;false:不管比
* @return
*/
public List<RowContent> readExcel(int sheetIndex, boolean isCloseStream) {
try {
long s1 = System.nanoTime();
Workbook wb = getXLSWorkBook(this.filePath, this.inp); if (wb == null)
return null;
Sheet sheet = getXLSSheet(wb, sheetIndex); List<RowContent> rowsContent = readSheetContent(sheet); long s2 = System.nanoTime();
logger.debug("readSheetContent coast times:" + (s2 - s1) / 1000000); return rowsContent;
} catch(Exception e)
{
logger.error("readExcel 异常", e);
return null;
} finally
{
if(isCloseStream)
{
destory();
}
}
} /**
* 重载,默认读取完成后,关闭流
*
* @return
*/
public List<RowContent> readExcel(int sheetIndex) {
return readExcel(sheetIndex, true);
} /**
*
* @param sheet
* @return
*/
public List<RowContent> readSheetContent(Sheet sheet) {
if (sheet == null) {
return null;
} List<RowContent> rowsContent = new ArrayList<XLSOprUtil.RowContent>(); int itemNum = sheet.getLastRowNum();
logger.info("Sheet名称:{}, 行数:{}", sheet.getSheetName(), itemNum); for (Row row : sheet) {
int cellNum = row.getLastCellNum();
String[] cells = new String[cellNum];
int index = 0;
boolean isAllEmpty = true; // 判断某一行内容是否为空
for (Cell cell : row) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
// System.out.print("数字型单元格内容:" + cell.getNumericCellValue()
// + " ");
cells[index++] = String.valueOf(cell.getNumericCellValue());
isAllEmpty = false;
break;
case Cell.CELL_TYPE_STRING:
// System.out.print("字符串型单元格内容:" + cell.getStringCellValue()
// + " ");
cells[index++] = String.valueOf(cell.getStringCellValue());
isAllEmpty = false;
break;
default:
index++;
break;
}
} if (!isAllEmpty) {
RowContent rowContent = new RowContent();
rowContent.setRowCells(cells);
rowsContent.add(rowContent);
}
} return rowsContent;
} /**
*
*/
public void destory() {
if (inp != null) {
try {
inp.close();
logger.debug("--- 关闭读取的文件流 成功 ----");
} catch (Exception e) {
logger.error(e.toString());
}
}
} /**
* 适配不同的excel文档版本
*
* @param filename
* @param inp
* @return
* @throws IOException
*/
public Workbook getXLSWorkBook(String filename, InputStream inp)
throws IOException {
if (filename.matches("^(.*.xls)$")) {
return new HSSFWorkbook(inp);
} else {
return new XSSFWorkbook(inp);
}
} /**
* 获取指定的工作表
*
* @param wb
* @param number
* @return
*/
public Sheet getXLSSheet(Workbook wb, int number) {
if (wb != null) {
return wb.getSheetAt(number);
}
return null;
} @SuppressWarnings("serial")
public class RowContent implements Serializable{
private String[] rowCells; /**
* @return the rowCells
*/
public String[] getRowCells() {
return rowCells;
} /**
* @param rowCells
* the rowCells to set
*/
public void setRowCells(String[] rowCells) {
this.rowCells = rowCells;
}
}
}

三、使用

excel读取的更多相关文章

  1. java的poi技术下载Excel模板上传Excel读取Excel中内容(SSM框架)

    使用到的jar包 JSP: client.jsp <%@ page language="java" contentType="text/html; charset= ...

  2. excel读取 工具类

    package cn.yongche.utils; import java.io.File; import java.io.FileInputStream; import java.io.IOExce ...

  3. NPOI 2.0 Excel读取显示

    NPOI 2.0 Excel读取显示   最近接到需求,需要把excel表格里的数据原样展示到web页面,主要是满足随意跨行跨列. 之前用过一点NPOI,不过接触的不太多,趁这次机会再熟悉一下.由于操 ...

  4. Pandas之Dateframe 实现Excel读取与写入

    目的:有时需对数据进行到出到Excel,直观的给别人参阅,或从Excel中读取数据进行操作和分析依赖库 pandas 可简单的读出和写入 1,根据Excel读取( 需安装xlrd库) import n ...

  5. EPPlus实战篇——Excel读取

    .net core 项目 可以从excel读取任何类型(T)的数据,只要T中的field的[Display(Name = "1233")]中的name==excel column ...

  6. php excel 读取日期问题

    在 php excel 读取 xls 格式的文件时,xls 上面显示的是正常的日期格式 但是读取出来的话,就会是一个万位整形数据,这显然不是我们想要的日期 读取出来的结果: 41807 $t = 41 ...

  7. 利用poi包装一个简单的Excel读取器.一(适配一个Reader并提供readLine方法)

    通常,读文本我们会使用BufferedReader,它装饰或者说管理了InputStreamReader,同时提供readLine()简化了我们对文本行的读取.就像从流水线上获取产品一样,每当取完一件 ...

  8. C#连接Excel读取与写入数据库SQL ( 上 )

    第一次写C#与sql的东西,主要任务是从Excel读取数据,再存到SQL server中. 先上读取Excel文件的code如下. public bool GetFiles(string equipN ...

  9. Excel 读取写入数据库

    // Excel 读取写入数据库 // 3.8版本的poi  4.0 可以不用写  parseCell  这个方法,可以直接赋值 STRING 类型 import org.apache.poi.hss ...

随机推荐

  1. Zend框架设置数据库连接编码为utf8三种方法

    第一种:$conn['host'] = '127.0.0.1';$conn['username'] = '56_' . $tenant['tenant'];$conn['password'] = $t ...

  2. dev GridControl实现拖拽

    一.示例说明 以gridControl1和gridControl2为例,从gridControl1拖拽行到gridControl2中去. 二.属性设置 gridControl2.AllowDrop = ...

  3. &和&&的区别

    &和&&都可以用作逻辑与的运算符,表示逻辑与(and),当运算符两边的表达式的结果都为true时,整个运算结果才为true,否则,只要有一方为false,则结果为false. ...

  4. INNO SETUP 读取可变注册表路径的问题

    ;INNO 读取可变注册表路径的问题 ;问题:;我想自动为 FireFox 安装上 Real 的 Mozilla 插件~但是它的路径存放在"HKEY_CURRENT_USER\Softwar ...

  5. C语言-两个库函数

    两个库函数 --1-- printf函数 1.1 printf 函数的介绍 1.2 格式控制字符串 1.3 %f输出精度的问题 1.4 printf 函数使用注意事项 --2-- scanf函数 2. ...

  6. list中的中文转换编码显示

    for i in range(1,sheet.nrows): row=sheet.row_values(i,0,sheet.ncols) row=str(row).replace('u\'','\'' ...

  7. spring配置文件

    pom文件: <properties> <commons-lang.version>2.6</commons-lang.version> <slf4j.ver ...

  8. location对象说明

    在浏览器的console层输入 location 即可输出该对象的相关信息 location.protocol   协议类型  http/https location.hostname 主机名 loc ...

  9. Lucky and Good Months by Gregorian Calendar - POJ3393模拟

    Lucky and Good Months by Gregorian Calendar Time Limit: 1000MS Memory Limit: 65536K Description Have ...

  10. JAVA基础知识之Annotation

    基本Annotation Annotation必须使用工具(APT, Annotation tool)才能处理,Annotation可以在编译,类加载,运行时被读取,并执行相应处理. 下面介绍一些常用 ...