java讀取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文件,解決辦法:
添加jar文件,java導入導出Excel文件要引入jxl.jar包,最關鍵的是這套API是純Java的,並不依賴Windows系統,即使運行在Linux下,它同樣能夠正確的處理Excel文件。
jxl對Excel表格的認識,每個單元格的位置認為是由一個二維坐標(i,j)給定,其中i表示列,如歲j表示行,並且從上到下遞增,從左到右遞增。
對於合並單元格的以最左,最上的單元格的坐標為准。如下圖中t.xls,一班名單(0,0),陳茵(1,2),陳開先(1,6)。
4.java代碼對t.xls的讀取
❸ java中怎麼讀取excel文件
package com.jqgj.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
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 ImportNameTest {
/**
* Excel 2003
*/
private final static String XLS = "xls";
/**
* Excel 2007
*/
private final static String XLSX = "xlsx";
/**
* 分隔符
*/
private final static String SEPARATOR = "|";
/**
* 由Excel文件的Sheet導出至List
*
* @param file
* @param sheetNum
* @return
*/
public static List<String> exportListFromExcel(File file, int sheetNum)
throws IOException {
return exportListFromExcel(new FileInputStream(file),
FilenameUtils.getExtension(file.getName()), sheetNum);
}
/**
* 由Excel流的Sheet導出至List
*
* @param is
* @param extensionName
* @param sheetNum
* @return
* @throws IOException
*/
public static List<String> exportListFromExcel(InputStream is,
String extensionName, int sheetNum) throws IOException {
Workbook workbook = null;
if (extensionName.toLowerCase().equals(XLS)) {
workbook = new HSSFWorkbook(is);
} else if (extensionName.toLowerCase().equals(XLSX)) {
workbook = new XSSFWorkbook(is);
}
return exportListFromExcel(workbook, sheetNum);
}
/**
* 由指定的Sheet導出至List
*
* @param workbook
* @param sheetNum
* @return
* @throws IOException
*/
private static List<String> exportListFromExcel(Workbook workbook,
int sheetNum) {
Sheet sheet = workbook.getSheetAt(sheetNum);
// 解析公式結果
FormulaEvaluator evaluator = workbook.getCreationHelper()
.createFormulaEvaluator();
List<String> list = new ArrayList<String>();
int minRowIx = sheet.getFirstRowNum();
int maxRowIx = sheet.getLastRowNum();
for (int rowIx = minRowIx; rowIx <= maxRowIx; rowIx++) {
Row row = sheet.getRow(rowIx);
StringBuilder sb = new StringBuilder();
short minColIx = row.getFirstCellNum();
short maxColIx = row.getLastCellNum();
for (short colIx = minColIx; colIx <= maxColIx; colIx++) {
Cell cell = row.getCell(new Integer(colIx));
CellValue cellValue = evaluator.evaluate(cell);
if (cellValue == null) {
continue;
}
// 經過公式解析,最後只存在Boolean、Numeric和String三種數據類型,此外就是Error了
// 其餘數據類型,根據官方文檔,完全可以忽略http://poi.apache.org/spreadsheet/eval.html
switch (cellValue.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
sb.append(SEPARATOR + cellValue.getBooleanValue());
break;
case Cell.CELL_TYPE_NUMERIC:
// 這里的日期類型會被轉換為數字類型,需要判別後區分處理
if (DateUtil.isCellDateFormatted(cell)) {
sb.append(SEPARATOR + cell.getDateCellValue());
} else {
//把手機號碼轉換為字元串
DecimalFormat df = new DecimalFormat("#");
sb.append(SEPARATOR + df.format(cellValue.getNumberValue()));
}
break;
case Cell.CELL_TYPE_STRING:
sb.append(SEPARATOR + cellValue.getStringValue());
break;
case Cell.CELL_TYPE_FORMULA:
break;
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_ERROR:
break;
default:
break;
}
}
list.add(sb.toString());
}
return list;
}
/**
* @param args
*/
public static void main(String[] args) {
String path = "f:\\telName.xlsx";
try {
List<String> listS= exportListFromExcel(new File(path),0);
for(int i=0;i<listS.size();i++){
System.out.println(listS.get(i));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
❹ 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文件
參考代碼及注釋如下:
importJava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStream;
importorg.apache.poi.hssf.usermodel.HSSFWorkbook;
importorg.apache.poi.ss.usermodel.Cell;
importorg.apache.poi.ss.usermodel.Row;
importorg.apache.poi.ss.usermodel.Sheet;
importorg.apache.poi.ss.usermodel.Workbook;
publicclassReadExcel{
publicstaticvoidreadExcel(Filefile){
try{
InputStreaminputStream=newFileInputStream(file);
StringfileName=file.getName();
Workbookwb=null;
//poi-3.9.jar只可以讀取2007以下的版本,後綴為:xsl
wb=newHSSFWorkbook(inputStream);//解析xls格式
Sheetsheet=wb.getSheetAt(0);//第一個工作表,第二個則為1,以此類推...
intfirstRowIndex=sheet.getFirstRowNum();
intlastRowIndex=sheet.getLastRowNum();
for(intrIndex=firstRowIndex;rIndex<=lastRowIndex;rIndex++){
Rowrow=sheet.getRow(rIndex);
if(row!=null){
intfirstCellIndex=row.getFirstCellNum();
//intlastCellIndex=row.getLastCellNum();
//此處參數cIndex決定可以取到excel的列數。
for(intcIndex=firstCellIndex;cIndex<3;cIndex++){
Cellcell=row.getCell(cIndex);
Stringvalue="";
if(cell!=null){
value=cell.toString();
System.out.print(value+" ");
}
}
System.out.println();
}
}
}catch(FileNotFoundExceptione){
//TODO自動生成catch塊
e.printStackTrace();
}catch(IOExceptione){
//TODO自動生成catch塊
e.printStackTrace();
}
}
publicstaticvoidmain(String[]args){
Filefile=newFile("D:/test.xls");
readExcel(file);
}
}
❻ java讀取和輸出excel表格的問題
Java Excel 是一個開源項目,通過它Java開發人員可以讀取Excel文件的內容、創建新的Excel文件、更新已經存在的Excel文件等,在項目中需要導入名為jxl.jar的包。在這里只是示例它的基本用法,其他高級的功能(圖片、公式、格式等)請參考Java Excel的幫助文檔。
如有一個用戶資料的Excel表,包含ID、用戶名、性別、郵件等信息,定義一個用戶JavaBean:
packagecom.monitor1394.excel;
/**
*
*用戶
*
*@authormonitor
*Createdon2010-12-22,9:57:58
*/
publicclassUser{
/**ID*/
privateintid;
/**用戶名*/
privateStringname;
/**性別1:男2:女*/
privateintsex;
/**郵件*/
privateStringemail;
publicUser(){
}
publicUser(intid,Stringname,intsex,Stringemail){
this.id=id;
this.name=name;
this.sex=sex;
this.email=email;
}
publicStringgetEmail(){
returnemail;
}
publicvoidsetEmail(Stringemail){
this.email=email;
}
publicintgetId(){
returnid;
}
publicvoidsetId(intid){
this.id=id;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicintgetSex(){
returnsex;
}
publicvoidsetSex(intsex){
this.sex=sex;
}
@Override
publicStringtoString(){
returnid+":"+name;
}
}
提供的Excel表操作類如下,某些單元格的格式可按自己意願指定:
packagecom.monitor1394.excel;
importjava.io.File;
importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.List;
importjxl.Sheet;
importjxl.Workbook;
importjxl.format.Alignment;
importjxl.format.Border;
importjxl.format.BorderLineStyle;
importjxl.format.Colour;
importjxl.format.VerticalAlignment;
importjxl.read.biff.BiffException;
importjxl.write.Label;
importjxl.write.Number;
importjxl.write.NumberFormats;
importjxl.write.WritableCellFormat;
importjxl.write.WritableFont;
importjxl.write.WritableSheet;
importjxl.write.WritableWorkbook;
importjxl.write.WriteException;
/**
*
*Excel表操作
*
*@authormonitor
*Createdon2010-12-22,9:50:28
*/
publicclassExcel{
/**標題單元格格式*/
=null;
/**主題內容單元格格式*/
=null;
/**注釋單元格格式*/
=null;
/**浮點型數據的單元格格式*/
=null;
/**整型數據的單元格格式*/
=null;
/**初始化數據*/
privatestaticbooleaninit=false;
/**私有構造方法,防止錯誤使用Excel類*/
privateExcel(){
}
/**
*初始化各單元格格式
*@throwsWriteException初始化失敗
*/
privatestaticvoidinit()throwsWriteException{
WritableFontfont1,font2,font3,font4;
//Arial字體,9號,粗體,單元格黃色,田字邊框,居中對齊
font1=newWritableFont(WritableFont.ARIAL,9,WritableFont.BOLD,false);
titleFormat=newWritableCellFormat(font1);
titleFormat.setBackground(Colour.YELLOW);
titleFormat.setBorder(Border.ALL,BorderLineStyle.THIN);
titleFormat.setAlignment(Alignment.CENTRE);
//Arial字體,9號,粗體,單元格黃色,田字邊框,左右居中對齊,垂直居中對齊,自動換行
font2=newWritableFont(WritableFont.ARIAL,9,WritableFont.BOLD,false);
noteFormat=newWritableCellFormat(font2);
noteFormat.setBackground(Colour.YELLOW);
noteFormat.setBorder(Border.ALL,BorderLineStyle.THIN);
noteFormat.setAlignment(Alignment.CENTRE);
noteFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
noteFormat.setWrap(true);
//Arial字體,9號,非粗體,單元格淡綠色,田字邊框
font3=newWritableFont(WritableFont.ARIAL,9,WritableFont.NO_BOLD,false);
bodyFormat=newWritableCellFormat(font3);
bodyFormat.setBackground(Colour.LIGHT_GREEN);
bodyFormat.setBorder(Border.ALL,BorderLineStyle.THIN);
//Arial字體,9號,非粗體,單元格淡綠色,田字邊框
font4=newWritableFont(WritableFont.ARIAL,9,WritableFont.NO_BOLD,false);
floatFormat=newWritableCellFormat(font4,NumberFormats.FLOAT);
floatFormat.setBackground(Colour.LIGHT_GREEN);
floatFormat.setBorder(Border.ALL,BorderLineStyle.THIN);
//Arial字體,9號,非粗體,單元格淡綠色,田字邊框
font4=newWritableFont(WritableFont.ARIAL,9,WritableFont.NO_BOLD,false);
intFormat=newWritableCellFormat(font4,NumberFormats.INTEGER);
intFormat.setBackground(Colour.LIGHT_GREEN);
intFormat.setBorder(Border.ALL,BorderLineStyle.THIN);
init=true;
}
(List<User>userList,FiledestFile)throwsWriteException,IOException{
if(init==false)init();
intindex,row;
WritableSheetsheet=null;
WritableWorkbookbook=null;
book=Workbook.createWorkbook(destFile);
sheet=book.createSheet("用戶表",0);
sheet.setColumnView(0,15);
sheet.setColumnView(1,15);
sheet.setColumnView(2,15);
sheet.setColumnView(3,40);
//欄位變數名
index=0;
sheet.addCell(newLabel(index++,0,"id",titleFormat));
sheet.addCell(newLabel(index++,0,"name",titleFormat));
sheet.addCell(newLabel(index++,0,"sex",titleFormat));
sheet.addCell(newLabel(index++,0,"email",titleFormat));
//欄位名
index=0;
sheet.addCell(newLabel(index++,1,"ID",titleFormat));
sheet.addCell(newLabel(index++,1,"用戶名",titleFormat));
sheet.addCell(newLabel(index++,1,"性別",titleFormat));
sheet.addCell(newLabel(index++,1,"郵件",titleFormat));
//欄位注釋
index=0;
sheet.addCell(newLabel(index++,2,null,noteFormat));
sheet.addCell(newLabel(index++,2,null,noteFormat));
sheet.addCell(newLabel(index++,2,"1:男/n2:女",noteFormat));
sheet.addCell(newLabel(index++,2,null,noteFormat));
row=3;
for(Useruser:userList){
if(user==null)continue;
index=0;
sheet.addCell(newNumber(index++,row,user.getId(),bodyFormat));
sheet.addCell(newLabel(index++,row,user.getName(),bodyFormat));
sheet.addCell(newNumber(index++,row,user.getSex(),bodyFormat));
sheet.addCell(newLabel(index++,row,user.getEmail(),bodyFormat));
row++;
}
book.write();
if(book!=null)book.close();
}
publicstaticList<User>readUserExcelFile(Filefile)throwsIOException,BiffException{
if(file==null)returnnull;
introw,column;
Stringtemp=null;
Workbookbook=null;
Sheetsheet=null;
List<User>userList=newArrayList<User>();
book=Workbook.getWorkbook(file);
sheet=book.getSheet(0);
row=3;
while(row<sheet.getRows()){
column=0;
Useruser=newUser();
//id
temp=sheet.getCell(column++,row).getContents().trim();
if(temp!=null&&!temp.equals("")&&temp.matches("//d+"))user.setId(Integer.parseInt(temp));
elsebreak;
//名稱
temp=sheet.getCell(column++,row).getContents().trim();
if(temp!=null&&!temp.equals(""))user.setName(temp);
//性別
temp=sheet.getCell(column++,row).getContents().trim();
if(temp!=null&&!temp.equals("")&&temp.matches("//d+"))user.setSex(Integer.parseInt(temp));
//郵件
temp=sheet.getCell(column++,row).getContents().trim();
if(temp!=null&&!temp.equals(""))user.setEmail(temp);
userList.add(user);
row++;
}
if(book!=null)book.close();
returnuserList;
}
}
要導入的Excel表格式如下:
❼ 如何用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);
}
}