導航:首頁 > 文件類型 > java代碼解析excel文件

java代碼解析excel文件

發布時間:2023-05-26 08:37:50

『壹』 怎麼用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;
}

『貳』 急求,大神幫忙,請問java如何解析後綴名為.xlsm的excel文件

Java 如何解析我不懂,但是 xlsm 是能夠保存 VBA 宏代碼的 Excel 格式。如果不需要 Excel 里的宏代碼,你可以另存為 xlsx 來解析試試?

『叄』 Java對Excel解析(求助)

這篇blog主要是講述java中poi讀取excel,而excel的版本包括:2003-2007和2010兩個版本, 即excel的後綴名為:xls和xlsx。

讀取excel和MySQL相關: java的poi技術讀取Excel數據到MySQL

代碼如下

/**
*
*/
packagecom.b510.common;

/**
*@authorHongten
*@created2014-5-21
*/
publicclassCommon{

publicstaticfinalStringOFFICE_EXCEL_2003_POSTFIX="xls";
publicstaticfinalStringOFFICE_EXCEL_2010_POSTFIX="xlsx";

publicstaticfinalStringEMPTY="";
publicstaticfinalStringPOINT=".";
publicstaticfinalStringLIB_PATH="lib";
_INFO_XLS_PATH=LIB_PATH+"/student_info"+POINT+OFFICE_EXCEL_2003_POSTFIX;
_INFO_XLSX_PATH=LIB_PATH+"/student_info"+POINT+OFFICE_EXCEL_2010_POSTFIX;
publicstaticfinalStringNOT_EXCEL_FILE=":NottheExcelfile!";
="Processing...";

}

/**
*
*/
packagecom.b510.excel;

importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.ArrayList;
importjava.util.List;

importorg.apache.poi.hssf.usermodel.HSSFCell;
importorg.apache.poi.hssf.usermodel.HSSFRow;
importorg.apache.poi.hssf.usermodel.HSSFSheet;
importorg.apache.poi.hssf.usermodel.HSSFWorkbook;
importorg.apache.poi.xssf.usermodel.XSSFCell;
importorg.apache.poi.xssf.usermodel.XSSFRow;
importorg.apache.poi.xssf.usermodel.XSSFSheet;
importorg.apache.poi.xssf.usermodel.XSSFWorkbook;

importcom.b510.common.Common;
importcom.b510.excel.util.Util;
importcom.b510.excel.vo.Student;

/**
*@authorHongten
*@created2014-5-20
*/
publicclassReadExcel{

/**
*readtheExcelfile
*@
*@return
*@throwsIOException
*/
publicList<Student>readExcel(Stringpath)throwsIOException{
if(path==null||Common.EMPTY.equals(path)){
returnnull;
}else{
Stringpostfix=Util.getPostfix(path);
if(!Common.EMPTY.equals(postfix)){
if(Common.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)){
returnreadXls(path);
}elseif(Common.OFFICE_EXCEL_2010_POSTFIX.equals(postfix)){
returnreadXlsx(path);
}
}else{
System.out.println(path+Common.NOT_EXCEL_FILE);
}
}
returnnull;
}

/**
*ReadtheExcel2010
*@
*@return
*@throwsIOException
*/
publicList<Student>readXlsx(Stringpath)throwsIOException{
System.out.println(Common.PROCESSING+path);
InputStreamis=newFileInputStream(path);
XSSFWorkbookxssfWorkbook=newXSSFWorkbook(is);
Studentstudent=null;
List<Student>list=newArrayList<Student>();
//ReadtheSheet
for(intnumSheet=0;numSheet<xssfWorkbook.getNumberOfSheets();numSheet++){
XSSFSheetxssfSheet=xssfWorkbook.getSheetAt(numSheet);
if(xssfSheet==null){
continue;
}
//ReadtheRow
for(introwNum=1;rowNum<=xssfSheet.getLastRowNum();rowNum++){
XSSFRowxssfRow=xssfSheet.getRow(rowNum);
if(xssfRow!=null){
student=newStudent();
XSSFCellno=xssfRow.getCell(0);
XSSFCellname=xssfRow.getCell(1);
XSSFCellage=xssfRow.getCell(2);
XSSFCellscore=xssfRow.getCell(3);
student.setNo(getValue(no));
student.setName(getValue(name));
student.setAge(getValue(age));
student.setScore(Float.valueOf(getValue(score)));
list.add(student);
}
}
}
returnlist;
}

/**
*ReadtheExcel2003-2007
*@parampaththepathoftheExcel
*@return
*@throwsIOException
*/
publicList<Student>readXls(Stringpath)throwsIOException{
System.out.println(Common.PROCESSING+path);
InputStreamis=newFileInputStream(path);
HSSFWorkbookhssfWorkbook=newHSSFWorkbook(is);
Studentstudent=null;
List<Student>list=newArrayList<Student>();
//ReadtheSheet
for(intnumSheet=0;numSheet<hssfWorkbook.getNumberOfSheets();numSheet++){
HSSFSheethssfSheet=hssfWorkbook.getSheetAt(numSheet);
if(hssfSheet==null){
continue;
}
//ReadtheRow
for(introwNum=1;rowNum<=hssfSheet.getLastRowNum();rowNum++){
HSSFRowhssfRow=hssfSheet.getRow(rowNum);
if(hssfRow!=null){
student=newStudent();
HSSFCellno=hssfRow.getCell(0);
HSSFCellname=hssfRow.getCell(1);
HSSFCellage=hssfRow.getCell(2);
HSSFCellscore=hssfRow.getCell(3);
student.setNo(getValue(no));
student.setName(getValue(name));
student.setAge(getValue(age));
student.setScore(Float.valueOf(getValue(score)));
list.add(student);
}
}
}
returnlist;
}

@SuppressWarnings("static-access")
privateStringgetValue(XSSFCellxssfRow){
if(xssfRow.getCellType()==xssfRow.CELL_TYPE_BOOLEAN){
returnString.valueOf(xssfRow.getBooleanCellValue());
}elseif(xssfRow.getCellType()==xssfRow.CELL_TYPE_NUMERIC){
returnString.valueOf(xssfRow.getNumericCellValue());
}else{
returnString.valueOf(xssfRow.getStringCellValue());
}
}

@SuppressWarnings("static-access")
privateStringgetValue(HSSFCellhssfCell){
if(hssfCell.getCellType()==hssfCell.CELL_TYPE_BOOLEAN){
returnString.valueOf(hssfCell.getBooleanCellValue());
}elseif(hssfCell.getCellType()==hssfCell.CELL_TYPE_NUMERIC){
returnString.valueOf(hssfCell.getNumericCellValue());
}else{
returnString.valueOf(hssfCell.getStringCellValue());
}
}
}

/**
*
*/
packagecom.b510.excel.client;

importjava.io.IOException;
importjava.util.List;

importcom.b510.common.Common;
importcom.b510.excel.ReadExcel;
importcom.b510.excel.vo.Student;

/**
*@authorHongten
*@created2014-5-21
*/
publicclassClient{

publicstaticvoidmain(String[]args)throwsIOException{
Stringexcel2003_2007=Common.STUDENT_INFO_XLS_PATH;
Stringexcel2010=Common.STUDENT_INFO_XLSX_PATH;
//readthe2003-2007excel
List<Student>list=newReadExcel().readExcel(excel2003_2007);
if(list!=null){
for(Studentstudent:list){
System.out.println("No.:"+student.getNo()+",name:"+student.getName()+",age:"+student.getAge()+",score:"+student.getScore());
}
}
System.out.println("======================================");
//readthe2010excel
List<Student>list1=newReadExcel().readExcel(excel2010);
if(list1!=null){
for(Studentstudent:list1){
System.out.println("No.:"+student.getNo()+",name:"+student.getName()+",age:"+student.getAge()+",score:"+student.getScore());
}
}
}
}

/**
*
*/
packagecom.b510.excel.util;

importcom.b510.common.Common;

/**
*@authorHongten
*@created2014-5-21
*/
publicclassUtil{

/**
*getpostfixofthepath
*@parampath
*@return
*/
publicstaticStringgetPostfix(Stringpath){
if(path==null||Common.EMPTY.equals(path.trim())){
returnCommon.EMPTY;
}
if(path.contains(Common.POINT)){
returnpath.substring(path.lastIndexOf(Common.POINT)+1,path.length());
}
returnCommon.EMPTY;
}
}

/**
*
*/
packagecom.b510.excel.vo;

/**
*Student
*
*@authorHongten
*@created2014-5-18
*/
publicclassStudent{
/**
*id
*/
privateIntegerid;
/**
*學號
*/
privateStringno;
/**
*姓名
*/
privateStringname;
/**
*學院
*/
privateStringage;
/**
*成績
*/
privatefloatscore;

publicIntegergetId(){
returnid;
}

publicvoidsetId(Integerid){
this.id=id;
}

publicStringgetNo(){
returnno;
}

publicvoidsetNo(Stringno){
this.no=no;
}

publicStringgetName(){
returnname;
}

publicvoidsetName(Stringname){
this.name=name;
}

publicStringgetAge(){
returnage;
}

publicvoidsetAge(Stringage){
this.age=age;
}

publicfloatgetScore(){
returnscore;
}

publicvoidsetScore(floatscore){
this.score=score;
}

}

『肆』 java使用poi解析或處理excel的時候,如何防止數字變成科學計數法的

思路為:為了防止數字變成科學計數法方式表示,在源文件以及java代碼中都用文本的方式去生成和襲察解析excel,具體如下:

1.生成Excel時,設置單元格格式為STRING,即:

//關鍵代碼
HSSFCellcell=newHSSFCell();
cell.setCellType(HSSFCell.CELL_TYPE_STRING);

2.同理,解析察脊的時候,首先要保證源excel文件中該單元格格式是文本類型的,然後在java代碼里用STRING類型去解敗禪滲析:

//關鍵代碼
Stringvalue=cell.getStringCellValue();

『伍』 java解析.xlsb格式的excel文件

通過這個例子,演示以下如何用java生成excel文件:
import org.apache.poi.hssf.usermodel.*;
import java.io.FileOutputStream;
import java.io.IOException;
publicclass CreateCells
{
publicstaticvoid main(String[] args)
throws IOException
{
HSSFWorkbook wb = new HSSFWorkbook();//建立新HSSFWorkbook對象
HSSFSheet sheet = wb.createSheet("new sheet");//建立新的sheet對象
// Create a row and put some cells in it. Rows are 0 based.
HSSFRow row = sheet.createRow((short)0);//建立新行
// Create a cell and put a value in it.
HSSFCell cell = row.createCell((short)0);//建立新cell
cell.setCellValue(1);//設置cell的整數類型的值
// Or do it on one line.
row.createCell((short)1).setCellValue(1.2);//設置cell浮點類型的值
row.createCell((short)2).setCellValue("test");//設置cell字元類型的值
row.createCell((short)3).setCellValue(true);//設置cell布爾類型的值
HSSFCellStyle cellStyle = wb.createCellStyle();//建立新的cell樣式
cellStyle.setDataFormat(HSSFDataFormat.getFormat("m/d/yy h:mm"));//設置cell樣式為定製的日期格式
HSSFCell dCell =row.createCell((short)4);
dCell.setCellValue(new Date());//設置cell為日期類型的值
dCell.setCellStyle(cellStyle); //設置該cell日期的顯示格式
HSSFCell csCell =row.createCell((short)5);
csCell.setEncoding(HSSFCell.ENCODING_UTF_16);//設置cell編碼解決中文高位位元組截斷
csCell.setCellValue("中文測試_Chinese Words Test");//設置中西文結合字元串
row.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_ERROR);//建立錯誤cell
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
}
}
從以上例子,可以清楚的看到xls文件從大到小包擴了 HSSFWorkbook HSSFSheet HSSFRow HSSFCell這樣幾個對象。還可以在cell中設置各種類型的值。尤其要注意的是如果你想正確的顯示非歐美的字元時,尤其象中日韓這樣的語言,必須 設置編碼為16位的即是HSSFCell.ENCODING_UTF_16,才能保證字元的高8位不被截斷而引起編碼失真形成亂碼。
其他測試可以通過參考examples包中的測試例子掌握poi的詳細用法,包括字體的設置,cell大小和低紋的設置等。需要注意的是POI是一 個仍然在完善中的公開代碼的項目,所以有些功能正在不斷的擴充。如HSSFSheet的getFooter() getHeader()和 setFooter(HSSFFooter hsf) setHeader(HSSFHeader hsh)是在POI1.7中才有的,而POI1.5中就沒有。運行測試熟悉代碼或者使用它做項目時請注意POI的版本。
另外需要注意的是HSSF也有它的對xls基於事件的解析。可以參考常式中的EventExample.java。它通過實現 HSSFListener完成從普通流認知Xls中包含的內容,在apache Cocoon中的 org.apache.cocoon.serialization.HSSFSerializer中用到了這個解析。因為Cocoon2 是基於事件的,所以POI為了提供快速的解析也提供了相應的事件。當然我們自己也可以實現這個事件介面。
因為POI還不是一個足夠成熟的項目,所以有必要做進一步的開發和測試。但是它已經為我們用純java操作ole2對象提供了可能,而且克服了ole對象調用的缺陷,提供了伺服器端的Excel解決方案。
利用Java 創建和讀取Excel文檔
為了保證示例程序的運行,必須安裝Java 2 sdk1.4.0 和Jakarta POI,Jakarta POI的Web站點是: http://jakarta.apache.org/poi/
示例1將演示如何利用Jakarta POI API 創建Excel 文檔。
示例1程序如下:
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.FileOutputStream;
publicclass CreateXL {
/** Excel 文件要存放的位置,假定在D盤JTest目錄下*/
publicstatic String outputFile="D:/JTest/ gongye.xls";
publicstaticvoid main(String argv[])
{
try
{
// 創建新的Excel 工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
// 在Excel工作簿中建一工作表,其名為預設值
// 如要新建一名為"效益指標"的工作表,其語句為:
// HSSFSheet sheet = workbook.createSheet("效益指標");
HSSFSheet sheet = workbook.createSheet();
// 在索引0的位置創建行(最頂端的行)
HSSFRow row = sheet.createRow((short)0);
//在索引0的位置創建單元格(左上端)
HSSFCell cell = row.createCell((short) 0);
// 定義單元格為字元串類型
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
// 在單元格中輸入一些內容
cell.setCellValue("增加值");
// 新建一輸出文件流
FileOutputStream fOut = new FileOutputStream(outputFile);
// 把相應的Excel 工作簿存檔
workbook.write(fOut);
fOut.flush();
// 操作結束,關閉文件
fOut.close();
System.out.println("文件生成...");
}catch(Exception e) {
System.out.println("已運行 xlCreate() : " + e );
}
}
}
這里演示創建和設置字體和單元格的格式,然後再應用這些格式:

1、創建字體,設置其為紅色、粗體:
HSSFFont font = workbook.createFont();
font.setColor(HSSFFont.COLOR_RED);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
2、創建格式
HSSFCellStyle cellStyle= workbook.createCellStyle();
cellStyle.setFont(font);
3、應用格式
HSSFCell cell = row.createCell((short) 0);
cell.setCellStyle(cellStyle);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue("標題 ");

總之,如本篇文章所演示的一樣,Java程序員不必擔心Excel工作表中的數據了,利用Jakarta POI API, 就可以輕易的在程序中存取Excel文檔。

『陸』 java 怎樣解析 excel生成的xml文件

java解析excel生成的xml文件的方法是使用dom4j實現的。
dom4j是一個簡單的開源庫,用於處理XML、 XPath和XSLT,它基於Java平台,使用Java的集合框架,全面集成了DOM,SAX和JAXP。
1、excel生成的xml樣例文件:
<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
<Created>2006-09-16T00:00:00Z</Created>
<LastSaved>2016-07-25T03:26:50Z</LastSaved>
<Version>14.00</Version>
</DocumentProperties>
<OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office">
<AllowPNG/>
<RemovePersonalInformation/>
</OfficeDocumentSettings>
<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
<WindowHeight>7956</WindowHeight>
<WindowWidth>14808</WindowWidth>
<WindowTopX>240</WindowTopX>
<WindowTopY>168</WindowTopY>
<ActiveSheet>2</ActiveSheet>
<ProtectStructure>False</ProtectStructure>
<ProtectWindows>False</ProtectWindows>
</ExcelWorkbook>
<Styles>
<Style ss:ID="Default" ss:Name="Normal">
<Alignment ss:Vertical="Bottom"/>
<Borders/>
<Font ss:FontName="宋體" x:CharSet="134" ss:Size="11" ss:Color="#000000"/>
<Interior/>
<NumberFormat/>
<Protection/>
</Style>
<Style ss:ID="s16" ss:Name="好">
<Font ss:FontName="宋體" x:CharSet="134" ss:Size="11" ss:Color="#006100"/>
<Interior ss:Color="#C6EFCE" ss:Pattern="Solid"/>
</Style>
<Style ss:ID="s17">
<Alignment ss:Horizontal="Left" ss:Vertical="Center" ss:Indent="1"
ss:WrapText="1"/>
<Font ss:FontName="宋體" x:CharSet="134" ss:Size="8" ss:Color="#686868"/>
<NumberFormat ss:Format="@"/>
</Style>
<Style ss:ID="s18" ss:Parent="s16">
<Alignment ss:Vertical="Bottom"/>
</Style>
<Style ss:ID="s19">
<NumberFormat ss:Format="yyyy/m/d\ h:mm:ss"/>
</Style>
</Styles>
<Worksheet ss:Name="Sheet1">
<Table ss:ExpandedColumnCount="6" ss:ExpandedRowCount="3" x:FullColumns="1"
x:FullRows="1" ss:DefaultRowHeight="14.4">
<Row>
<Cell><Data ss:Type="String">工號</Data></Cell>
<Cell><Data ss:Type="String">姓名 </Data></Cell>
<Cell ss:Index="5"><Data ss:Type="String">工號</Data></Cell>
<Cell><Data ss:Type="String">姓名</Data></Cell>
</Row>
<Row>
<Cell><Data ss:Type="Number">111</Data></Cell>
<Cell><Data ss:Type="String">張三</Data></Cell>
<Cell ss:Index="5"><Data ss:Type="Number">111</Data></Cell>
<Cell ss:Formula="=VLOOKUP(R2C5:R3C5,RC[-5]:R[1]C[-4],2)"><Data
ss:Type="String">張三</Data></Cell>
</Row>
<Row>
<Cell><Data ss:Type="Number">112</Data></Cell>
<Cell><Data ss:Type="String">李四</Data></Cell>
<Cell ss:Index="5"><Data ss:Type="Number">112</Data></Cell>
<Cell ss:Formula="=VLOOKUP(R2C5:R3C5,RC[-5]:R[1]C[-4],2)"><Data
ss:Type="String">李四</Data></Cell>
</Row>
</Table>
<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
<PageSetup>
<Header x:Margin="0.3"/>
<Footer x:Margin="0.3"/>
<PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/>
</PageSetup>
<Panes>
<Pane>
<Number>3</Number>
<ActiveRow>7</ActiveRow>
<ActiveCol>5</ActiveCol>
</Pane>
</Panes>
<ProtectObjects>False</ProtectObjects>
<ProtectScenarios>False</ProtectScenarios>
</WorksheetOptions>
</Worksheet>
</Workbook>
2、java解析代碼:
import java.io.File;
import java.util.Iterator;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Demo {
public static void main(String[] args) throws Exception {
SAXReader reader = new SAXReader();
Document document = reader.read(new File("person.xml"));
Element root = document.getRootElement();

Iterator it = root.elementIterator();
while (it.hasNext()) {
Element element = (Element) it.next();

//未知屬性名稱情況下
/*Iterator attrIt = element.attributeIterator();
while (attrIt.hasNext()) {
Attribute a = (Attribute) attrIt.next();
System.out.println(a.getValue());
}*/

//已知屬性名稱情況下
System.out.println("id: " + element.attributeValue("id"));

//未知元素名情況下
/*Iterator eleIt = element.elementIterator();
while (eleIt.hasNext()) {
Element e = (Element) eleIt.next();
System.out.println(e.getName() + ": " + e.getText());
}
System.out.println();*/

//已知元素名情況下
System.out.println("title: " + element.elementText("title"));
System.out.println("author: " + element.elementText("author"));
System.out.println();
}
}
}

『柒』 java代碼怎麼判斷文件的格式是excel文件

匹配後綴名。

String.endsWith(".xls");
xls
xlsx
xlsm

1.兩點需要注意

1.string.spilt("\.")分割字元串成子字元串數組,以「.」分割,必須版寫成string.spilt("\.")的方式權,不能寫成string.spilt(".")。斜線必須是反斜線且。

2.獲取分割後的字元串數組,要獲得最後一個item的index ,方式是int suffixIndex = strArray.length -1;

publicStringgetFileType(StringfileName){
String[]strArray=fileName.split("\.");
intsuffixIndex=strArray.length-1;
System.out.println(strArray[suffixIndex]);
return"strArray[suffixIndex]";
}

『捌』 java 如何解析 excel

用poi,poi是apache的項目,不但能對襲如excel操作,甚鋒禪裂至連PDF等其他格式文件都可以任意操作,jxl好像是一個韓國棒子開發的,畢銀閉竟他個人能力有限,而且很多大公司不認jxl

『玖』 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文件相關的資料

熱點內容
css文件的代碼格式 瀏覽:152
微信61安卓永不升級版 瀏覽:800
編程入門了可以做什麼 瀏覽:658
qq飛車飛碟怎麼買2017 瀏覽:727
上海哪個地方網路最好 瀏覽:983
java數據類型干什麼的 瀏覽:840
c怎麼列印文件怎麼打開 瀏覽:217
圖片列印PDF文件中間有個白條 瀏覽:955
柔道90版本搬磚裝備 瀏覽:377
win7remixos沒網路 瀏覽:427
蝙蝠需要什麼網路 瀏覽:873
監聽文件在按 瀏覽:236
什麼編程語言能直接控制電腦硬體 瀏覽:959
老驗鈔機如何升級系統 瀏覽:668
pst文件許可權 瀏覽:699
swot分析圖word版本 瀏覽:792
3dmax坦克建模教程 瀏覽:137
windows10版本14393 瀏覽:280
餘姚ug編程課程培訓哪裡學 瀏覽:759
java輸出到txt換行 瀏覽:663

友情鏈接