JXL exporting Excel code in Java

Source: Internet
Author: User
Tags string format

JXL is a Korean written by the Java operation of Excel Tools, in the open source world, there are two sets of more influential APIs to use, one is a poi, and the other is JEXCELAPI. Where the function is relatively weak relative to the POI. However, JEXCELAPI support for Chinese is very good, the API is pure Java, and does not rely on the Windows system, even if running under Linux, it can also correctly handle Excel files. It is also important to note that this set of APIs has limited support for graphics and charts, and only the PNG format is recognized. Use the following: Build the environment will download the file unpacked, get Jxl.jar, put into the classpath, the installation is complete.

First, create a file

To generate an Excel file named "Test.xls", where the first worksheet is named "first page" with the following general effect:

  1. Package COM.LUQIN.JXL;
  2. Import Java.io.File;
  3. Import JXL. Workbook;
  4. Import Jxl.format.UnderlineStyle;
  5. Import Jxl.write.Font;
  6. Import Jxl.write.Label;
  7. Import Jxl.write.WritableFont;
  8. Import Jxl.write.WritableSheet;
  9. Import Jxl.write.WritableWorkbook;
  10. /**
  11. * Create a simple instance of Excel
  12. *
  13. * @author Luqin * @version
  14. * @time 2012-6-20 11:12:02
  15. *
  16. */
  17. Public class Createexcel {
  18. public static void Main (string[] args) {
  19. String excelname = "Table.xls";
  20. try {
  21. File Excelfile = new File (Excelname);
  22. //If the file exists, delete it
  23. if (excelfile.exists ())
  24. Excelfile.delete ();
  25. //Open File
  26. Writableworkbook book = Workbook.createworkbook (Excelfile);
  27. //Generate a worksheet named "first page", parameter 0 indicates this is the first page
  28. Writablesheet sheet = book.createsheet ("First page", 0);
  29. //Merge cells
  30. Sheet.mergecells (5, 5, 6, 6);
  31. //Text style
  32. Jxl.write.WritableFont WFC = new Jxl.write.WritableFont (
  33. Writablefont.arial, Ten, Writablefont.no_bold, false,
  34. Underlinestyle.no_underline, Jxl.format.Colour.RED);
  35. Jxl.write.WritableCellFormat WCFFC = new Jxl.write.WritableCellFormat (
  36. WFC);
  37. //Set cell style
  38. Wcffc.setbackground (JXL.FORMAT.COLOUR.GRAY_25); //Cell color
  39. Wcffc.setalignment (Jxl.format.Alignment.CENTRE); //Cell Center
  40. //In the construction child of the label object, the cell position is the first column, the first row (0,0)
  41. //And the contents of the cell are
  42. Label label = New Label (0, 0, "Head1", WCFFC);
  43. //Add a defined cell to the worksheet
  44. Sheet.addcell (label);
  45. /**//* 
  46. * Generate a cell that holds numbers must use the full package path of number, otherwise there is a syntax ambiguity cell position is the second column, the first row, the value is 789.123
  47. */
  48. Jxl.write.Number number = new Jxl.write.Number (1, 0, 555.12541);
  49. Sheet.addcell (number);
  50. //write data and close file
  51. Book.write ();
  52. Book.close ();
  53. System.out.println ("Excel created successfully");
  54. } catch (Exception e) {
  55. System.out.println (e);
  56. }
  57. }
  58. }

After the compilation is executed, an Excel file is generated.

Third, read the file

Take the Excel file we just created as an example, do a simple read operation, the program code is as follows:

  1. Package test;
  2. //Read the class of Excel
  3. import Java.io.File;
  4. import JXL.  Cell;
  5. import JXL.  Sheet;
  6. import JXL.  Workbook;
  7. public class Readexcel {
  8. public static void Main (String args[]) {
  9. try {
  10. Workbook book = Workbook.getworkbook ( new File ( "Test.xls"));
  11. //Get first Sheet object
  12. Sheet Sheet = Book.getsheet ( 0);
  13. //Get the first row of cells in the first column
  14. Cell cell1 = Sheet.getcell ( 0, 0);
  15. String result = Cell1.getcontents ();
  16. SYSTEM.OUT.PRINTLN (result);
  17. Book.close ();
  18. } catch (Exception e) {
  19. System.out.println (e);
  20. }
  21. }
  22. }


Program execution Result: test

Iv. Modification of documents
Using JEXCELAPI can modify an existing Excel file, when you modify the Excel file, in addition to opening the file in a different way,
The other actions are the same as creating Excel. The following example adds a worksheet to the Excel file that we have generated:

  1. Package test;
  2. Import Java.io.File;
  3. Import JXL. Workbook;
  4. Import Jxl.write.Label;
  5. Import Jxl.write.WritableSheet;
  6. Import Jxl.write.WritableWorkbook;
  7. Public class Updateexcel {
  8. public static void Main (String args[]) {
  9. try {
  10. //Excel Get File
  11. Workbook wb = Workbook.getworkbook ( new File ( "Test.xls"));
  12. //Open a copy of a file and specify the data to write back to the original file
  13. Writableworkbook book = Workbook.createworkbook ( new File ( "Test.xls"),
  14. WB);
  15. //Add a worksheet
  16. Writablesheet sheet = book.createsheet ( "second page", 1);
  17. Sheet.addcell ( new Label ( 0, 0, "test data for the second page"));
  18. Book.write ();
  19. Book.close ();
  20. } catch (Exception e) {
  21. System.out.println (e);
  22. }
  23. }


Other operations

First, data formatting

There are no complex data types involved in Excel, and the ability to handle strings, numbers, and dates is a good fit for general applications.

1. String formatting

The formatting of strings involves elements such as font, weight, and font size, which are mainly composed of Writablefont and
Writablecellformat class to be responsible. Suppose we use the following statement when generating a cell containing a string,
For the convenience of narration, we add a number for each line of the command:

    1. Writablefont font1 =
    2. New Writablefont (Writablefont.times, writablefont.bold); ①
    3. Writablecellformat format1 = new Writablecellformat (font1); ②
    4. Label label = New Label ( 0, 0, "Data 4 test", FORMAT1) ③


Where ① specifies the string format: times, font size 16, bold display. Writablefont has a very rich
constructors, for different situations, have a detailed list of Jexcelapi's Java-doc, which are no longer listed here.

The ② code uses the Writablecellformat class, which is very important, which allows you to specify a variety of cells
property, there are more descriptions in subsequent cell formatting.

The ③ uses the constructor of the label class, specifying that the string is given that format.

In the Writablecellformat class, there is also an important way to specify the alignment of the data, such as for our
The above instance, you can specify:

    1. Assign Horizontal alignment to center
    2. Format1.setalignment (Jxl.format.Alignment.CENTRE);
    3. //Assign vertical alignment to center
    4. Format1.setverticalalignment (Jxl.format.VerticalAlignment.CENTRE);


Second, cell operation

An important part of Excel is the operation of cells, such as row height, column width, cell merging, etc., fortunately Jexcelapi
These support are provided. These operations are relatively straightforward and only the relevant APIs are described below.

1. Merging cells

    1. Writablesheet.mergecells (int m, int n, int p, int q);
    2. The function is to merge all the cells from (M,n) to (P,Q), such as:
    3. Writablesheet sheet = book.createsheet ("first page", 0);
    4. Merge all cells from the first row to the first row of column sixth
    5. Sheet.mergecells (0, 0, 5, 0);


A merge can be either horizontal or vertical. Merged cells cannot be merged again, otherwise an exception is triggered.

2, Row height and column width

Writablesheet.setrowview (int i,int height);

The function is to specify the height of line i+1, for example:

Set the height of the first row to 200
Sheet.setrowview (0,200);

Writablesheet.setcolumnview (int i,int width);

The function is to specify the width of column i+1, for example:

Set the width of the first column to 30
Sheet.setcolumnview (0,30);

JEXCELAPI also has other features, such as inserting images, which are not introduced here and can be explored by the reader.

Where: If you are reading an Excel, you need to know how many rows and how many columns it has, such as the following:

Workbook book = Workbook.getworkbook (New File ("Test 1.xls"));
Get the first sheet object
Sheet Sheet = book.getsheet (0);
Get the first row of cells in the first column
int columnum = Sheet.getcolumns ();//Get column number
int rownum = Sheet.getrows ();//Gets the number of rows
System.out.println (Columnum);
System.out.println (rownum);
for (int i = 0; i < rownum; i++)//loop for Read and write
{
            for  (int j  =  0; j  <  columnum; j++)  {
Cell cell1 = Sheet.getcell (j, I);
String result = Cell1.getcontents ();
System.out.print (result);
System.out.print ("\ t");
}
System.out.println ();
}
Book.close ();

Exporting Excel code in Java with JXL

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.