java如何读取整个excel文件的内容

如题所述

本例使用java来读取excel的内容并展出出结果,代码如下:

复制代码 代码如下:

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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.poifs.filesystem.POIFSFileSystem;

public class ExcelOperate {

public static void main(String[] args) throws Exception {
File file = new File("ExcelDemo.xls");
String[][] result = getData(file, 1);
int rowLength = result.length;
for(int i=0;i<rowLength;i++) {
for(int j=0;j<result[i].length;j++) {
System.out.print(result[i][j]+"\t\t");
}
System.out.println();
}

}
/**
* 读取Excel的内容,第一维数组存储的是一行中格列的值,二维数组存储的是多少个行
* @param file 读取数据的源Excel
* @param ignoreRows 读取数据忽略的行数,比喻行头不需要读入 忽略的行数为1
* @return 读出的Excel中数据的内容
* @throws FileNotFoundException
* @throws IOException
*/
public static String[][] getData(File file, int ignoreRows)
throws FileNotFoundException, IOException {
List<String[]> result = new ArrayList<String[]>();
int rowSize = 0;
BufferedInputStream in = new BufferedInputStream(new FileInputStream(
file));
// 打开HSSFWorkbook
POIFSFileSystem fs = new POIFSFileSystem(in);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFCell cell = null;
for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
HSSFSheet st = wb.getSheetAt(sheetIndex);
// 第一行为标题,不取
for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {
HSSFRow row = st.getRow(rowIndex);
if (row == null) {
continue;
}
int tempRowSize = row.getLastCellNum() + 1;
if (tempRowSize > rowSize) {
rowSize = tempRowSize;
}
String[] values = new String[rowSize];
Arrays.fill(values, "");
boolean hasValue = false;
for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {
String value = "";
cell = row.getCell(columnIndex);
if (cell != null) {
// 注意:一定要设成这个,否则可能会出现乱码
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
if (date != null) {
value = new SimpleDateFormat("yyyy-MM-dd")
.format(date);
} else {
value = "";
}
} else {
value = new DecimalFormat("0").format(cell
.getNumericCellValue());
}
break;
case HSSFCell.CELL_TYPE_FORMULA:
// 导入时如果为公式生成的数据则无值
if (!cell.getStringCellValue().equals("")) {
value = cell.getStringCellValue();
} else {
value = cell.getNumericCellValue() + "";
}
break;
case HSSFCell.CELL_TYPE_BLANK:
break;
case HSSFCell.CELL_TYPE_ERROR:
value = "";
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
value = (cell.getBooleanCellValue() == true ? "Y"
: "N");
break;
default:
value = "";
}
}
if (columnIndex == 0 && value.trim().equals("")) {
break;
}
values[columnIndex] = rightTrim(value);
hasValue = true;
}

if (hasValue) {
result.add(values);
}
}
}
in.close();
String[][] returnArray = new String[result.size()][rowSize];
for (int i = 0; i < returnArray.length; i++) {
returnArray[i] = (String[]) result.get(i);
}
return returnArray;
}

/**
* 去掉字符串右边的空格
* @param str 要处理的字符串
* @return 处理后的字符串
*/
public static String rightTrim(String str) {
if (str == null) {
return "";
}
int length = str.length();
for (int i = length - 1; i >= 0; i--) {
if (str.charAt(i) != 0x20) {
break;
}
length--;
}
return str.substring(0, length);
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-07-03

工具:

参考代码及注释如下:

import Java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 
 
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; 
public class ReadExcel {
  public static void readExcel(File file){ 
         try { 
             InputStream inputStream = new FileInputStream(file); 
             String fileName = file.getName(); 
             Workbook wb = null; 
            // poi-3.9.jar  只可以读取2007以下的版本,后缀为:xsl
             wb = new HSSFWorkbook(inputStream);//解析xls格式 
           
             Sheet sheet = wb.getSheetAt(0);//第一个工作表  ,第二个则为1,以此类推...
              
             int firstRowIndex = sheet.getFirstRowNum(); 
             int lastRowIndex = sheet.getLastRowNum(); 
             for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex ++){ 
                 Row row = sheet.getRow(rIndex); 
                 if(row != null){ 
                     int firstCellIndex = row.getFirstCellNum(); 
                    // int lastCellIndex = row.getLastCellNum(); 
                     //此处参数cIndex决定可以取到excel的列数。
                     for(int cIndex = firstCellIndex; cIndex < 3; cIndex ++){ 
                         Cell cell = row.getCell(cIndex); 
                         String value = ""; 
                         if(cell != null){ 
                             value = cell.toString(); 
                             System.out.print(value+"\t"); 
                         } 
                     } 
                     System.out.println(); 
                 } 
             } 
         } catch (FileNotFoundException e) { 
             // TODO 自动生成 catch 块 
             e.printStackTrace(); 
         } catch (IOException e) { 
             // TODO 自动生成 catch 块 
             e.printStackTrace(); 
         } 
     } 
  public static void main(String[] args) {
  File file = new File("D:/test.xls");
  readExcel(file);
 }
}

第2个回答  2018-03-31

在Java中读取Excel文件的内容

在这里,我使用的是一个叫Java Excel API的东西,类似的还有jakarta的POI,不过感觉那个

太复杂了点儿。而且jxl对中文的支持相当的好,至少我在用的过程中一点问题没出。

一、下载地址

http://www.andykhan.com/jexcelapi/

二、特性

可以读取Excel 95, 97, 2000文件

可以读或写Excel 97及其以后版本的的公式(不过我发现好像有bug)

生成Excel 97格式的电子表格

支持字体、数字和日期格式化

支持单元格的颜色和阴影

可以编辑现有的文件

三、读文件

//声明一下,记得后面要关闭哦。。

Workbook workbook = null;

try {

workbook = Workbook.getWorkbook(new File("d:\\temp\\TestRead.xls"));

} catch (Exception e) {

throw new Exception("file to import not found!");

}

Sheet sheet = workbook.getSheet(0);

Cell cell = null;

int columnCount=3;

int rowCount=sheet.getRows();

for (int i = 0; i<rowcount; p="" {

for (int j = 0; j<columncount; p="" {

//注意,这里的两个参数,第一个是表示列的,第二才表示行

cell=sheet.getCell(j, i);

//要根据单元格的类型分别做处理,否则格式化过的内容可能会不正确

if(cell.getType()==CellType.NUMBER){

System.out.print(((NumberCell)cell).getValue());

}

else if(cell.getType()==CellType.DATE){

System.out.print(((DateCell)cell).getDate());

}

else{

System.out.print(cell.getContents());

}

//System.out.print(cell.getContents());

System.out.print("\t");

}

System.out.print("\n");

}

//关闭它,否则会有内存泄露

workbook.close();

本回答被网友采纳
第3个回答  2016-04-30
这个问题在java贴吧里常见,并且有很多方式完成,这里就给你贴一份,你试着在贴吧里和百度知道里,学习程序方面的问题解答。
public String[][] readExcel(String filePath) {
String[][] s = null;
try {
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(
filePath));
HSSFSheet sheet = workbook.getSheetAt(0);
int rows = sheet.getPhysicalNumberOfRows();
s = new String[rows][];
if (rows > 0) {
// 获取总列数`
int cells = sheet.getRow(0).getPhysicalNumberOfCells();
for (int r =0; r < rows; r++) {

HSSFRow row = sheet.getRow(r);
String[] cellsvalue = new String[cells+1];
for (short c = 0; c < cells; c++) {
String value = "";
HSSFCell cell = row.getCell(c);
if (cell != null) {
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_FORMULA:
//
break;
case HSSFCell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
value = new java.text.SimpleDateFormat(
"yyyy-MM-dd").format(cell
.getDateCellValue());
} else {
value = String.valueOf(cell
.getNumericCellValue());
}
break;
case HSSFCell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BLANK:
value="";
default:
break;
}
if (cell == null) {
value="";
}
}
cellsvalue[c] = value;
if(value.endsWith(".0")){
cellsvalue[c] = value.substring(0, value.length()-2);
}
}
s[r] = cellsvalue;
java.io.File myfile = new java.io.File(filePath);
if (myfile.exists()) {
myfile.delete();
}
}
}
} catch (Exception ex) {
// TODO 自动生成 catch 块

ex.printStackTrace();
}
return s;
}
第4个回答  2020-06-16

在java程序添加spire.xls.jar依赖,下面的代码可以读取整个工作表的数据

    import com.spire.xls.*;

     

    public class ReadExcel {

        public static void main(String[] args) {

     

            //创建Workbook对象

            Workbook wb = new Workbook();

            //加载一个Excel文档

            wb.loadFromFile("C:\\Users\\Administrator\\Desktop\\test.xlsx");

            //获取第一个工作表

            Worksheet sheet = wb.getWorksheets().get(0);

            //遍历工作表的每一行

            for (int i = 1; i < sheet.getLastRow() + 1; i++) {

                //遍历工作的每一列

                for (int j = 1; j < sheet.getLastColumn() + 1; j++) {

                    //输出指定单元格的数据

                    System.out.print(sheet.get(i,j).getText());

                    System.out.print("\t");

                }

                System.out.print("\n");

            }

        }

    }

相似回答