Java读取Excel文件资料地几种方法.docx
《Java读取Excel文件资料地几种方法.docx》由会员分享,可在线阅读,更多相关《Java读取Excel文件资料地几种方法.docx(13页珍藏版)》请在冰豆网上搜索。
Java读取Excel文件资料地几种方法
Java读取Excel文件的几种方法
最近单位有个项目需要读取excel文件的容,特别对java读取excel文件的方法做了一点学习,也为了其他人以后能更简单地开发,少走弯路,特写此文,以下程序经过了我的测试,可以保证程序可用,如果你照搬都不行,可能是你的环境有问题。
读取excel文件的常用开源免费方法有以下几种:
JDBC-ODBCExcelDriver
jxl.jar
jcom.jar
poi.jar
下面分别对这几种方法分别进行探讨
1、JDBC-ODBCExcelDriver
这种方法是将excel看成是数据库进行操作,使用SQLSelect语句即可查询excel表格。
优点是:
不需要第三方的jar包。
如下表样
首先在控制面板进行数据源ODBC登记
具体方法如下:
下面就是代码了。
packagexuzhe;
importjava.io.*;
importjava.sql.*;
//javaxuzhe.ExcelJDBC
publicclassExcelJDBC{
publicstaticvoidmain(String[]args)throwsSQLException{
Connectioncon=null;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:
odbc:
ExcelJDBC");
Statementst=con.createStatement();
ResultSetrs=st.executeQuery("Select*from[Sheet1$]");
ResultSetMetaDatarsmd=rs.getMetaData();
intnumberOfColumns=rsmd.getColumnCount();
System.out.println("表格列数"+numberOfColumns);
System.out.println(rsmd.getColumnName
(1)+","+rsmd.getColumnName
(2)+","+rsmd.getColumnName(3));
while(rs.next()){
for(inti=1;i<=numberOfColumns;i++){
if(i>1)System.out.print(",");
StringcolumnValue=rs.getString(i);
System.out.print(columnValue);
}
System.out.println("");
}
rs.close();
st.close();
}
catch(Exceptionex){
System.err.print("Exception:
");
System.err.println(ex.getMessage());
}
finally{
con.close();
}
}
}
执行结果如下:
2、jxl.jar
jxl.jar为开源代码,任何运行java虚拟机的操作系统都能使用这个jar包操作excel表格。
优点是:
不依赖其他任何第三方的库。
下载地址:
mirrors.ibiblio.org/pub/mirrors/maven2/net/sourceforge/jexcelapi/jxl/2.6.10/jxl-2.6.10.jar
程序如下:
packagexuzhe;
importjava.io.File;
importjxl.Sheet;
importjxl.Workbook;
//java-classpath.;E:
\eclipse3.6.2\workspace\CrazyJava\lib\jxl.jarxuzhe.ExcelJXL
publicclassExcelJXL
{
staticStringsourceFile="c:
\\name.xls";//源文件
publicstaticvoidmain(String[]args)
{
try
{
Workbookbook=Workbook.getWorkbook(newFile(sourceFile));
//0代表第一个工作表对象
Sheetsheet=book.getSheet(0);
introws=sheet.getRows();
intcols=sheet.getColumns();
Stringcolname1=sheet.getCell(0,0).getContents().trim();
Stringcolname2=sheet.getCell(1,0).getContents().trim();
Stringcolname3=sheet.getCell(2,0).getContents().trim();
System.out.println(colname1+","+colname2+","+colname3);
for(intz=1;z{
//0代表列数,z代表行数
Stringname=sheet.getCell(0,z).getContents();
Stringsex=sheet.getCell(1,z).getContents();
StringID=sheet.getCell(2,z).getContents();
System.out.println(name+","+sex+","+ID);
}
}
catch(Exceptione)
{
e.printStackTrace();
}
}
}
执行结果如下:
3、jcom.jar
jcom.jar是日本人开发的,也是一个开源项目,下载地址:
将jcom.jar拷贝到classlib目录下,将jcom.dll放到你的JAVA_HOME/bin目录下,否则会出现下面错误。
程序如下:
packagexuzhe;
importjp.ne.so_net.ga2.no_ji.jcom.excel8.*;
importjp.ne.so_net.ga2.no_ji.jcom.*;
importjava.io.File;
importjava.util.Date;
publicclassExcelJCOM{
publicstaticvoidmain(String[]args)throwsException{
JCOMReadExcel();
JCOMCreateExcel();
}
staticvoidJCOMReadExcel()
{
ReleaseManagerrm=newReleaseManager();
try
{
System.out.println("EXCELstartup...");
//ifalreadystarted,opennewwindow
ExcelApplicationexcel=newExcelApplication(rm);
excel.Visible(true);
StringFilename="c:
\\name.xls";
ExcelWorkbooksxlBooks=excel.Workbooks();
ExcelWorkbookxlBook=xlBooks.Open(Filename);
ExcelWorksheetsxlSheets=xlBook.Worksheets();
//第一个工作表
ExcelWorksheetxlSheet=xlSheets.Item
(1);
ExcelRangexlRange=xlSheet.Cells();
inti;
intj;
for(j=1;j<=4;j++)
{
for(i=1;i<=3;i++)
{
System.out.print(xlRange.Item(j,i).Value());
if(i<3)
{
System.out.print(",");
}
}
System.out.println("");
}
}
catch(Exceptione){e.printStackTrace();}
finally{rm.release();}
}
staticvoidJCOMCreateExcel()
{
ReleaseManagerrm=newReleaseManager();
try{
System.out.println("EXCELstartup...");
//ifalreadystarted,opennewwindow
ExcelApplicationexcel=newExcelApplication(rm);
excel.Visible(true);
//displayanyinformation
System.out.println("Version="+excel.Version());
System.out.println("UserName="+excel.UserName());
System.out.println("Caption="+excel.Caption());
System.out.println("Value="+excel.Value());
ExcelWorkbooksxlBooks=excel.Workbooks();
ExcelWorkbookxlBook=xlBooks.Add();//createnewbook
//enumurateallfiles
System.out.println
("setinfomationoffilesincurrentdirectorytocell...");
ExcelWorksheetsxlSheets=xlBook.Worksheets();
ExcelWorksheetxlSheet=xlSheets.Item
(1);
ExcelRangexlRange=xlSheet.Cells();
xlRange.Item(1,1).Value("filename");
xlRange.Item(2,1).Value("size");
xlRange.Item(3,1).Value("lastmodifiedtime");
xlRange.Item(4,1).Value("isdirectory");
xlRange.Item(5,1).Value("isfile");
xlRange.Item(6,1).Value("canread");
xlRange.Item(7,1).Value("canwrite");
Filepath=newFile("./");
String[]filenames=path.list();
for(inti=0;iFilefile=newFile(filenames[i]);
System.out.println(file);
xlRange.Item(1,i+2).Value(file.getName());
xlRange.Item(2,i+2).Value((int)file.length());
xlRange.Item(3,i+2).Value(newDate(file.lastModified()));
xlRange.Item(4,i+2).Value(file.isDirectory()?
"Yes":
"No");
xlRange.Item(5,i+2).Value(file.isFile()?
"Yes":
"No");
xlRange.Item(6,i+2).Value(file.canRead()?
"Yes":
"No");
xlRange.Item(7,i+2).Value(file.canWrite()?
"Yes":
"No");
}
charstart='B';
charend=(char)((byte)start+filenames.length-1);
System.out.println("end=["+end+"]");
Stringexpression="=Sum(B2:
"+String.valueOf(end)+"2)";
System.out.println("expression=["+expression+"]");
System.out.println
("embedequation,calculatesumoffilesize:
"+expression);
xlRange.Item(1,filenames.length+2).Value("sum");
xlRange.Item(2,filenames.length+2).Formula(expression);
xlRange.Columns().AutoFit();//fitcolumns
//commentout,ifprintout.
//outputdefaultprinter.
//System.out.println("printout...");
//xlSheet.PrintOut();
//commentout,ifbooksavetofile.
//ifnopath,saveto(MyDocuments)
//System.out.println
//("savetofile...(MyDocuments)\\testExcel.xls");
xlBook.SaveAs("testExcel.xls");
xlBook.Close(false,null,false);
excel.Quit();
System.out.println("thankyou.");
}
catch(Exceptione){e.printStackTrace();}
finally{rm.release();}
}
}
执行结果如下:
4、poi.jar
poi.jar是apache旗下的一个开源项目,下载地址:
.apache.org/dyn/closer.cgi/poi/release/bin/poi-bin-3.8-20120326.zip
程序如下:
packagexuzhe;
importorg.apache.poi.hssf.usermodel.*;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importorg.apache.poi.hssf.usermodel.HSSFCell;
importorg.apache.poi.hssf.usermodel.HSSFRow;
importorg.apache.poi.hssf.usermodel.HSSFSheet;
importorg.apache.poi.hssf.usermodel.HSSFWorkbook;
//
publicclassExcelPOI{
/**
*paramargs
*throwsIOException
*javaxuzhe.ExcelPOI
*/
SuppressWarnings("deprecation")
publicstaticvoidmain(String[]args)throwsIOException{
//TODOAuto-generatedmethodstub
ExcelPOI.POICreateExcel();
ExcelPOI.POIReadExcel();
}
publicstaticvoidPOICreateExcel()throwsIOException
{
HSSFWorkbookwb=newHSSFWorkbook();
HSSFSheetsheet=wb.createSheet("newsheet");
//0行
HSSFRowrow=sheet.createRow((short)0);
//1列
row.createCell((short)1).setCellValue("HelloWorld");
FileOutputStreamfileOut=newFileOutputStream("c:
\\workbook.xls");
wb.write(fileOut);
fileOut.close();
}
privatestaticHSSFWorkbookreadFile(Stringfilename)throwsIOException{
returnnewHSSFWorkbook(newFileInputStream(filename));
}
publicstaticvoidPOIReadExcel()throwsIOException
{
StringfileName="c:
\\name.xls";
HSSFWorkbookwb=ExcelPOI.readFile(fileName);
System.out.println("Datadump:
\n");
for(intk=0;k{
HSSFSheetsheet=wb.getSheetAt(k);
introws=sheet.getPhysicalNumberOfRows();
System.out.println("Sheet"+k+"\""+wb.getSheetName(k)+"\"has"+rows
+"row(s).");
for(intr=0;r{
HSSFRowrow=sheet.getRow(r);
if(row==null){
continue;
}
intcells=row.getPhysicalNumberOfCells();
System.out.println("\nROW"+row.getRowNum()+"has"+cells
+"cell(s).");
for(intc=0;c{
HSSFCellcell=row.getCell(c);
Stringvalue=null;
switch(cell.getCellType())
{
caseHSSFCell.CELL_TYPE_FORMULA:
value="FORMULAvalue="+cell.getCellFormula();
break;
caseHSSFCell.CELL_TYPE_NUMERIC:
value="NUMERICvalue="+cell.getNumericCellValue();
break;
caseHSSFCell.CELL_TYPE_STRING:
value="STRINGvalue="+cell.getStringCellValue();
break;
default:
}
System.out.println("CELLcol="+cell.getColumnIndex()+"VALUE="
+value);
}
}
}
}
}
执行结果如下:
以上就是我的一点心得体会,有误的地方请指正,来信发xuzhe_hn..。