Sometimes a project needs to export data to an Excel file, or read data from an Excel file.
OK, so now let's use a simple example to illustrate how Java reads Excel documents.
Search the Web Jxl.jar this jar package, which provides Java access to Excel files in the API.
Add the Jxl.jar to the engineering classpath.
First of all, talk about the conceptual stuff.
workbook, corresponding to an Excel document.
Writableworkbook: A writable Excel document.
A sheet:excel form.
Writablesheet: a writable form.
A cell in a label:excel file.
Code on: Java Create and write data to Excel
Import Java.io.File;
Import JXL. workbook;
Import Jxl.write.Label;
Import Jxl.write.WritableSheet;
Import Jxl.write.WritableWorkbook;
public class Createexcel
{public
static void Main (string[] args) throws Exception
{
String str[][] = {{ "HelloWorld", "AAA"}, {"Welcome", "BBB"}};
File F = new file ("Test.xls");
Writableworkbook workbook = Workbook.createworkbook (f);
Writablesheet sheet = workbook.createsheet ("Helloworldsheet", 0);
Label lab = null;
for (int i = 0; i < str.length. i++)
{for
(int j = 0; J < Str[i].length; J +)
{
Lab = new Label (J, I, Str[i][j]);
Sheet.addcell (Lab);
}
Workbook.write ();
Workbook.close ();
}
Java code to read data from an Excel document
Import Java.io.File;
Import JXL. Sheet;
Import JXL. workbook;
public class Readexcel
{public
static void Main (string[] args) throws Exception
{Workbook
workbook = Wo Rkbook.getworkbook (New File ("Test.xls"));
Sheet sheet[] = Workbook.getsheets ();
String lab = null;
for (int a = 0; a < sheet.length. a++)
{for
(int i = 0; i < sheet[a].getrows (); i++)
{for
(int j = 0; J < Sheet[a].getcolumns (); J + +)
{
Lab = Sheet[a].getcell (J, i). getcontents ();
System.out.print (Lab + ":");
}
System.out.println ();}}}