Write operation:
Package com.zhao.poi;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Org.apache.commons.io.FileUtils;
Import Org.apache.poi.hssf.usermodel.HSSFCell;
Import Org.apache.poi.hssf.usermodel.HSSFCellStyle;
Import Org.apache.poi.hssf.usermodel.HSSFRow;
Import Org.apache.poi.hssf.usermodel.HSSFSheet;
Import Org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class Poiexcle {
/*
*poi Writing excle file contents
*/
public static void Main (string[] args) {
Create a workbook
Hssfworkbook workbook=new Hssfworkbook ();
Create sheet
Hssfsheet Sheet=workbook.createsheet ();
Create first row rows
Hssfrow header=sheet.createrow (0);
Create a cell and insert a table header
Hssfcell Cell=null;
String[] infos={"id", "name", "Gender"};
for (int i=0;i<infos.length;i++) {
Cell=header.createcell (i);
Cell.setcellvalue (Infos[i]);
}
//
Hssfrow Body=null;
for (int i=1;i<=10;i++) {
Body=sheet.createrow (i);
Cell=body.createcell (0);
Cell.setcellvalue (i+ "");
Cell=body.createcell (1);
Cell.setcellvalue ("User_" +i);
Cell=body.createcell (2);
Cell.setcellvalue (i+ "");
}
Create a file
File File=new file ("D:\\poi_1119.xls");
try {
File.createnewfile ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
File output stream
try {
FileOutputStream stream=fileutils.openoutputstream (file);
Write
Workbook.write (stream);
Turn off the output stream
Stream.Close ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
Read operation:
Package com.zhao.poi;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import Org.apache.commons.io.FileUtils;
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 Poiread {
public static void Main (string[] args) {
Get file
File File=new file ("D:\\poi_1119.xls");
File input stream
try {
FileInputStream stream=fileutils.openinputstream (file);
Working thin
Hssfworkbook workbook=new Hssfworkbook (stream);
Sheet
Hssfsheet Sheet=workbook.getsheet ("Sheet0");
Hssfsheet sheet=workbook.getsheetat (0);
//
int firstrownumber=0;
int Lastrownumber=sheet.getlastrownum ();
for (int i=firstrownumber;i<lastrownumber;i++) {
Hssfrow Row=sheet.getrow (i);
int firstcellnumber=0;
int Lastcellnumber=row.getlastcellnum ();
//
for (int j=firstcellnumber;j<lastcellnumber;j++) {
Hssfcell Cell=row.getcell (j);
String Value=cell.getstringcellvalue ();
System.out.print (value+ "\ t");
}
System.out.println ("");
}
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
Java implementation of Excel file read and write operations