A simple example of Java reading the contents of an Excel file _java

Source: Internet
Author: User

With the help of Apathe's Poi.jar, the upload file does not support. jar so please download and change the file to. jar, add the Poi.jar package to the application, and put the Excel file you want to read into the root directory

This example uses Java to read the contents of Excel and display the results, the code reads as follows:

Copy Code code as follows:

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

}
/**
* Read the contents of Excel, the first dimension array is stored in a row of the value of the grid column, the two-dimensional array stores how many rows
* @param file to read data from the source Excel
* @param ignorerows Read the number of rows ignored, figurative wardrobe does not need to read the ignored number of rows is 1
* @return Read the contents of the data in 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));
Open 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);
First act title, do not take
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) {
Note: Be sure to set this, otherwise there may be garbled
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:
When importing, the data generated for the formula is not worth
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;
}

/**
* Remove the space to the right of the string
* @param str The string to be processed
* @return The processed string
*/
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);
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.