導航:首頁 > 編程語言 > java取excel數據

java取excel數據

發布時間:2022-11-19 14:23:01

java怎麼讀取excel數據

引入poi的jar包,大致如下:

importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStream;
importjava.math.BigDecimal;
importjava.text.DecimalFormat;
importjava.text.SimpleDateFormat;

importorg.apache.poi.xssf.usermodel.XSSFCell;
importorg.apache.poi.xssf.usermodel.XSSFRow;
importorg.apache.poi.xssf.usermodel.XSSFSheet;
importorg.apache.poi.xssf.usermodel.XSSFWorkbook;

publicclassExcelUtil2007{
/**讀取excel文件流的指定索引的sheet
*@paraminputStreamexcel文件流
*@paramsheetIndex要讀取的sheet的索引
*@return
*@throwsFileNotFoundException
*@throwsIOException
*/
(InputStreaminputStream,intsheetIndex)throwsFileNotFoundException,IOException
{
returnreadExcel(inputStream).getSheetAt(sheetIndex);
}
/**讀取excel文件的指定索引的sheet
*@paramfilePathexcel文件路徑
*@paramsheetIndex要讀取的sheet的索引
*@return
*@throwsIOException
*@throwsFileNotFoundException
*/
(StringfilePath,intsheetIndex)throwsFileNotFoundException,IOException
{
returnreadExcel(filePath).getSheetAt(sheetIndex);
}
/**讀取excel文件的指定索引的sheet
*@paramfilePathexcel文件路徑
*@paramsheetName要讀取的sheet的名稱
*@return
*@throwsIOException
*@throwsFileNotFoundException
*/
(StringfilePath,StringsheetName)throwsFileNotFoundException,IOException
{
returnreadExcel(filePath).getSheet(sheetName);
}
/**讀取excel文件,返回XSSFWorkbook對象
*@paramfilePathexcel文件路徑
*@return
*@throwsFileNotFoundException
*@throwsIOException
*/
(StringfilePath)throwsFileNotFoundException,IOException
{
XSSFWorkbookwb=newXSSFWorkbook(newFileInputStream(filePath));
returnwb;
}
/**讀取excel文件流,返回XSSFWorkbook對象
*@paraminputStreamexcel文件流
*@return
*@throwsFileNotFoundException
*@throwsIOException
*/
(InputStreaminputStream)throwsFileNotFoundException,IOException
{
XSSFWorkbookwb=newXSSFWorkbook(inputStream);
returnwb;
}
/***讀取excel中指定的單元格,並返回字元串形式的值
*1.數字
*2.字元
*3.公式(返回的為公式內容,非單元格的值)
*4.空
*@paramst要讀取的sheet對象
*@paramrowIndex行索引
*@paramcolIndex列索引
*@paramisDate是否要取的是日期(是則返回yyyy-MM-dd格式的字元串)
*@return
*/
(XSSFSheetst,introwIndex,intcolIndex,booleanisDate){
Strings="";
XSSFRowrow=st.getRow(rowIndex);
if(row==null)return"";
XSSFCellcell=row.getCell(colIndex);
if(cell==null)return"";
if(cell.getCellType()==0){//數字
if(isDate)s=newSimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue());
elses=trimPointO(String.valueOf(getStringValue(cell)).trim());
}elseif(cell.getCellType()==1){//字元(excel中的空格,不是全形,也不是半形,不知道是神馬,反正就是""這個)
s=cell.getRichStringCellValue().getString().replaceAll("","").trim();
// s=cell.getStringCellValue();//07API新增,好像跟上一句一致
}
elseif(cell.getCellType()==2){//公式
s=cell.getCellFormula();
}
elseif(cell.getCellType()==3){//空
s="";
}
returns;
}
/**如果數字以.0結尾,則去掉.0
*@params
*@return
*/
publicstaticStringtrimPointO(Strings){
if(s.endsWith(".0"))
returns.substring(0,s.length()-2);
else
returns;
}

/**處理科學計數法和百分比模式的數字單元格
*@paramcell
*@return
*/
(XSSFCellcell){
StringsValue=null;
shortdataFormat=cell.getCellStyle().getDataFormat();
doubled=cell.getNumericCellValue();
BigDecimalb=newBigDecimal(Double.toString(d));
//百分比樣式的
if(dataFormat==0xa||dataFormat==9){
b=b.multiply(newBigDecimal(100));
//Stringtemp=b.toPlainString();
DecimalFormatdf=newDecimalFormat("0.00");//保留兩位小數的百分比格式
sValue=df.format(b)+"%";
}else{
sValue=b.toPlainString();
}
returnsValue;
}
}

Ⅱ 用JAVA如何取得EXCEL 中指定的幾行的數據

可以使用poi來解析excel:
//獲取指定行,索引從0開始
hssfRow=hssfSheet.getRow(1);
//獲取總行數,獲取的是最後一行的編號(編號從0開始)
int rowNum = sheet.getLastRowNum();

然後拿到excel對象循環解析從50開始到100即可。

Ⅲ java如何讀取整個excel文件的內容

工具:
參考代碼及注釋如下:
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); }}

Ⅳ java怎麼獲取excel中的數據

使用java poi
package webservice;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelController {

@SuppressWarnings("deprecation")
public void excel() throws FileNotFoundException, IOException{

String filename = "d:\\excel.xls";
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(filename));
//按名引用excel工作表
// HSSFSheet sheet = workbook.getSheet("JSP");
//用式獲取excel工作表採用工作表索引值
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row ;
HSSFCell cell1;
int rows=sheet.getLastRowNum();
for(int icount=0;icount<rows;icount++){
row = sheet.getRow(icount);
int line=row.getPhysicalNumberOfCells();
for(int j=0;j<line;j++){
cell1= row.getCell(j);
System.out.println(cell1+"--"+icount+"---"+j);
}
}
//列印讀取值
// System.out.println(cell.getStringCellValue());

//新建輸流
FileOutputStream fout = new FileOutputStream(filename); //PS:filename 另存路徑處理直接寫入模版文件
//存檔
workbook.write(fout);
fout.flush();
//結束關閉
fout.close();

}

public HSSFCell getCell(HSSFRow row, int index) {

// 取發期單元格
HSSFCell cell = row.getCell(index);

// 單元格存
if (cell == null) {

// 創建單元格
cell = row.createCell(index);
}

// 返單元格
return cell;
}

public static void main(String[] args) {
ExcelController ec = new ExcelController();
try {
ec.excel();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Ⅳ 怎麼用java將一個excel裡面數據讀出並寫入另一個excel

需要對Excel中的數據進行讀取操作。

Ⅵ java如何讀取整個excel文件的內容

在java程序添加spire.xls.jar依賴

importcom.spire.xls.*;

publicclassReadExcel{
publicstaticvoidmain(String[]args){

//創建Workbook對象
Workbookwb=newWorkbook();
//載入一個Excel文檔
wb.loadFromFile("C:\Users\Administrator\Desktop\test.xlsx");
//獲取第一個工作表
Worksheetsheet=wb.getWorksheets().get(0);
//遍歷工作表的每一行
for(inti=1;i<sheet.getLastRow()+1;i++){
//遍歷工作的每一列
for(intj=1;j<sheet.getLastColumn()+1;j++){
//輸出指定單元格的數據
System.out.print(sheet.get(i,j).getText());
System.out.print(" ");
}
System.out.print(" ");
}
}
}

Ⅶ 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);
}
}

Ⅷ java中怎樣從Excel中讀寫數據

JavaEXCELAPI簡介
JavaExcel是一開放源碼項目,通過它Java開發人員可以讀取Excel文件的內容、創建新的Excel文件、更新已經存在的Excel文件。使用該API非Windows操作系統也可以通過純Java應用來處理Excel數據表。因為是使用Java編寫的,所以我們在Web應用中可以通過JSP、Servlet來調用API實現對Excel數據表的訪問。

應用示例
從Excel文件讀取數據表

Java ExcelAPI既可以從本地文件系統的一個文件(.xls),也可以從輸入流中讀取Excel數據表。讀取Excel數據表的第一步是創建Workbook(術語:工作薄),下面的代碼片段舉例說明了應該如何操作: 需要用到一個開源的jar包,jxl.jar。

Filefile=newFile("c:\a.xls");
InputStreamin=newFileInputStream(file);
Workbookworkbook=Workbook.getWorkbook(in);
//獲取第一張Sheet表
Sheetsheet=workbook.getSheet(0);

//我們既可能通過Sheet的名稱來訪問它,也可以通過下標來訪問它。如果通過下標來訪問的話,要注意的一點是下標從0開始,就像數組一樣。
//獲取第一行,第一列的值
Cellc00=rs.getCell(0,0);
Stringstrc00=c00.getContents();
//獲取第一行,第二列的值
Cellc10=rs.getCell(1,0);
Stringstrc10=c10.getContents();
//我們可以通過指定行和列得到指定的單元格Cell對象
Cellcell=sheet.getCell(column,row);
//也可以得到某一行或者某一列的所有單元格Cell對象
Cell[]cells=sheet.getColumn(column);
Cell[]cells2=sheet.getRow(row);
//然後再取每一個Cell中的值
Stringcontent=cell.getContents();

Ⅸ 如何用JAVA讀取EXCEL文件裡面的數據

使用poi能解決你的問題
或者是
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import static java.lang.System.out;

public class FileTest {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String string = "";
File file = new File("c:" + File.separator + "xxx.xls");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String str;
while((str = br.readLine()) != null) {
string += str;
}
out.println(string);
}

}

Ⅹ 如何使用java從excel表提取內容

以下是使用java從excel表提取內容的程序 -
import java.io.File;import java.io.FileInputStream;import org.apache.tika.metadata.Metadata;import org.apache.tika.parser.ParseContext;import org.apache.tika.parser.microsoft.ooxml.OOXMLParser;import org.apache.tika.sax.BodyContentHandler;public class ExtractContentFromExcel {
public static void main(String args[]) throws Exception {

// detecting the file type
BodyContentHandler handler = new BodyContentHandler();

Metadata metadata = new Metadata();
FileInputStream inputstream = new FileInputStream(new File("excelExample.xlsx"));

ParseContext pcontext = new ParseContext();

// OOXml parser
OOXMLParser msofficeparser = new OOXMLParser();

msofficeparser.parse(inputstream, handler, metadata, pcontext);
System.out.println("Contents of the document:" + handler.toString());
System.out.println("Metadata of the document:");
String[] metadataNames = metadata.names();

for (String name : metadataNames) {
System.out.println(name + ": " + metadata.get(name));
}
}}Java

原ODF文件:excelExample.xlsx 的內容如下 -

執行上面示例代碼,得到以下結果 -
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/F:/worksp/javaexamples/libs/tika_libs/tika-app-1.16.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/F:/worksp/javaexamples/libs/tika_libs/tika-server-1.16.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
九月 27, 2017 5:15:47 上午 org.apache.tika.config.InitializableProblemHandler$3 handleInitializableProblem
警告: JBIG2ImageReader not loaded. jbig2 files will be ignored
See http://pdfbox.apache.org/2.0/dependencies.html#jai-image-io
for optional dependencies.
TIFFImageWriter not loaded. tiff files will not be processed
See http://pdfbox.apache.org/2.0/dependencies.html#jai-image-io
for optional dependencies.
J2KImageReader not loaded. JPEG2000 files will not be processed.
See http://pdfbox.apache.org/2.0/dependencies.html#jai-image-io
for optional dependencies.

九月 27, 2017 5:15:47 上午 org.apache.tika.config.InitializableProblemHandler$3 handleInitializableProblem
警告: org.xerial's sqlite-jdbc is not loaded.
Please provide the jar on your classpath to parse sqlite files.
See tika-parsers/pom.xml for the correct version.
Contents of the document:Sheet1
編號 姓名 年齡 工作
1001 王傳大 22 Java軟體開發
1002 李小雙 29 項目經理
1020 張在傳 28 人事經理

Sheet2

Sheet3

Metadata of the document:
date: 2017-09-27T09:15:38Z
meta:creation-date: 2017-09-27T09:13:50Z
extended-properties:Application: Microsoft Excel
Creation-Date: 2017-09-27T09:13:50Z
dcterms:created: 2017-09-27T09:13:50Z
Last-Modified: 2017-09-27T09:15:38Z
dcterms:modified: 2017-09-27T09:15:38Z
Last-Save-Date: 2017-09-27T09:15:38Z
protected: false
meta:save-date: 2017-09-27T09:15:38Z
Application-Name: Microsoft Excel
modified: 2017-09-27T09:15:38Z
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
custom:KSOProctBuildVer: 2052-10.1.0.6489Shell

易百教程移動端:請掃描本頁面底部(右側)二維碼並關注微信公眾號,回復:"教程" 選擇相關教程閱讀或直接訪問:http://m.yii.com 。

閱讀全文

與java取excel數據相關的資料

熱點內容
超解壓兔子視頻 瀏覽:20
單片機怎麼測負脈沖 瀏覽:170
魅族備份的app在哪裡 瀏覽:736
java倒三角列印 瀏覽:112
通達信回封板主圖源碼 瀏覽:44
戰地什麼伺服器 瀏覽:299
安卓為什麼老是閃退怎麼辦 瀏覽:803
樂高機器人的編程軟體下載 瀏覽:223
工作中怎麼使用加密狗 瀏覽:735
雲伺服器的後台找不到 瀏覽:98
php逐行寫入文件 瀏覽:912
javaoracleweb 瀏覽:440
京東加密碼怎麼弄 瀏覽:467
單片機程序員培訓 瀏覽:992
PHP商城源代碼csdn 瀏覽:636
怎麼把電腦里文件夾挪出來 瀏覽:693
java流程處理 瀏覽:685
ftp創建本地文件夾 瀏覽:660
腰椎第一節壓縮 瀏覽:738
xp去掉加密屬性 瀏覽:117