Excel is widely used and sometimes needs to be made into a database. Here we introduce a java method for creating and reading Excel.
PIO is an open-source toolkit under the Apache Jakarta project, which encapsulates Excel operations well.
The PIO package can be downloaded from my resources!
To create an Excel file, follow these steps:
First, create a file input stream.
Create an Excel worksheet for the file output stream
Create a worksheet in the workbook and name it
Create a new row cyclically in the worksheet
Create columns in each row
Write Data to cells. Set the cell character set to "UTF_16". Otherwise, garbled characters may occur in the written Chinese.
The Code is as follows:
[Java] view plaincopy
Package com. Alibaba J. uti.pdf;
Import java. io. FileInputStream;
Import java. io. FileOutputStream;
Import java. io. IOException;
Import java. io. OutputStream;
Import org. apache. poi. hssf. usermodel .*;
/**
* Use the POI tool to create an Excel worksheet and add content to it.
* @ Author la
*
*/
Public class CreateExcel {
Private void createExcel () throws IOException {
String excelFile = "myexcel.xls ";
FileOutputStream fos = new FileOutputStream (excelFile );
HSSFWorkbook wb = new HSSFWorkbook (); // create a workbook
HSSFSheet sheet = wb. createSheet (); // create a worksheet
Wb. setSheetName (0, "sheet0"); // you can specify a worksheet name.
HSSFRow row = null;
HSSFCell cell = null;
For (int I = 0; I <10; I ++ ){
Row = sheet. createRow (I); // Add a row
Cell = row. createCell (short) 0); // Add a column
Cell. setEncoding (HSSFCell. ENCODING_UTF_16); // you can specify the cell character set.
Cell. setCellType (I); // write data to the cell
Cell = row. createCell (short) 0 );
Cell. setEncoding (HSSFCell. ENCODING_UTF_16 );
Cell. setCellValue ("th" + I + "row ");
}
Wb. write (fos );
Fos. close ();
}
/**
* @ Param args
* 2012-10-23
* Void
* @ Throws IOException
*/
Public static void main (String [] args) throws IOException {
New CreateExcel (). createExcel ();
}
}