Use the Jexcel API to operate the Excel file

xiaoxiao2021-03-05  57

Friends using the Windows operating system must not be unfamiliar with Excel, but to use Java language to manipulate the Excel file is not an easy task. Today, the Web is increasingly popular, the demand for the Excel file is increasing through the web, and the current more popular operation is to create a CSV (Comma Separated Values) file in the JSP or Servlet, and will file this file with MIME, TEXT / CSV type returns to the browser, then calls Excel and displays the CSV file. This is just to say that you can access the Excel file, but you can't really manipulate the Excel file. This article will give you a surprise, introduce you to an open source project ?? Java Excel API, use it, you can easily manipulate the Excel file. Java Excel API Introduction Java Excel is an open source project, through its Java developers, you can read the contents of the Excel file, create a new Excel file, update the existing Excel file. Using this API non-Windows operating system can also process the Excel data table by pure Java applications. Because it is written in Java, we can call the API to implement access to the Excel data table in a web application. The stable version released now is V2.0, providing the following features:

• Read data from the Format of Excel 95, 97, 2000; • Read the Excel formula (can read the formula after Excel 97);? Generate an Excel data table (format is Excel 97);? Support font, numbers , Formatted the date; support the shadow operation of the cell, as well as color operation;

You can read, but you can't generate formulas, any type of formula last calculated value can be read; Application Example Read Data Sheet From Excel File The Java Excel API can either the local file system (.xls) or from input Read the Excel data table in the stream. The first step in reading the Excel data is to create Workbook (Terminology: Working). The following code snippet is explained how to operate: (full code see Excelreading.java)

Import java.io. *; import jxl. *; ... ... ... ... ... ... Try {// Build a Workbook object, read-only Workbook object // Create Workbook from the local file // Create Workbook INPUTSTREAM IS = New FileInputStream from the input stream (Sourcefile ); jxl.workbook rwb = workbook.getworkbook (is);} catch (exception e) {E.PrintStackTrace ();}

Once you have created Workbook, we can access Excel Sheet by it. Refer to the following code snippet: // Get the first Sheet table sheet = rwb.getsheet (0); we may access it through the name of the Sheet, or you can access it through the subscript. If you are accessible by the subscript, you should pay attention to the starting mark from 0, just like an array. Once you get the Sheet, we can access Excel Cell (Terms: Cells) through it. Refer to the following code snippet: // Get the first line, the value of the first column Cell C00 = gtcell (0); string strc00 = c00.getContents (); // Get the first line, second column Value Cell C10 = rs.getcell (1, 0); string strc10 = c10.getContents (); // Gets the second line, the second column value Cell C11 = rs.getcell (1, 1); string strC11 = C11 .getContents (); System.out.println ("Cell (0, 0)" "value:" strc00 "; type:" c00.gettype (); system.out.println ("Cell (1 0) " " value: " strc10 "; type: " c10.gettype ()); system.out.println (" Cell (1, 1) " " value: " strc11 "; type : " C11.Gettype ()); if it is only the value of Cell, we can easily return any type of CELL value as a string by getContents () method. Cell (0, 0) in the sample code is text type, Cell (1, 0) is a digital type, Cell (1, 1) is a date type, through getContents (), three types of return values ​​are characters. If you need to know the exact type of Cell content, the API also provides a range of methods.

Refer to the following code segment: string strc00 = null; double strc10 = 0.00; Date strc11 = NULL; Cell C00 = rs.getcell (0, 0); Cell C10 = rs.getcell (1, 0); Cell C11 = RS. Getcell (1, 1); if (c00.gettype () == celltype.label) {Labelcell Labelc00 = (labelcell) C00; strc00 = labelc00.getstring ();} if (c10.gettype () == celltype.number ) {NMBERCELL NUMC10 = (Numbercell) C10; strc10 = Numc10.getValue ();} if (c11.gettype () == cellType.date) {datecell datec11 = (datecell) C11; strc11 = datec11.getdate (); System.out.println ("Cell (0, 0)" "value:" strc00 "; type:" c00.gettype ()); system.out.println ("Cell (1, 0)" "Value:" STRC10 "; TYPE:" C10.Gettype ()); System.out.Println ("Cell (1, 1)" "Value:" STRC11 "; TYPE:" C11. GetType ()); After obtaining the Cell object, the type of cell can be obtained through the getType () method, and then match the basic type provided by the API, forcibly converting into a corresponding type, finally call the corresponding value method Getxxx ( ), You can get the value of the determined type. The API provides the following basic types, corresponding to the data format of Excel. For details of each type, see Java Excel API Document. When you complete the processing of Excel spreadsheet data, you must use the close () method to close the previously created object to release the memory space occupied by the read data table, which is especially important when reading a large amount of data. . Refer to the following code segment: // When the operation is complete, turn off the object, release the occupied memory space RWB.Close (); Java Excel API provides many ways to access the Excel data table, here I only briefly introduce several common methods For other methods, please refer to Java Excel API Document in the appendix.

• Method for providing the Workbook class 1. INT getNumberOfsheets () gets the number of worksheets (Sheets) in Workbook, example: jxl.workbook rw B = jxl.workbook.getworkbook (new file (sourcefile); int shop = RWB.GETNUMBEROFSHEETS (); 2. Sheet [] getSheets () Returns an array of worksheets in Workbook, example: JXL.Workbook RWB = jxl.workbook.getWorkbook (New file (sourcefile); Sheet [] sheets = rwb.getsheets (); 3. String getversion () Returns the version number of the API that is being used, it seems that there is not much role. JXL.Workbook RWB = jxl.workbook.getworkbook (new file (sourcefile); string apiversion = rwb.getversion ();

• String getName () Get the name of Sheet, Sample: JXL.Workbook RWB = jxl.Workbook.getWorkbook (new file (sourcefile); jxl.sheet = rwb.getsheet (0); String Sheetname = rs.getname (); 2. Int getColumns () Gets the number of total columns included in the Sheet table, example: jxl.workbook rwb = jxl.Workbook.getworkbook (new file (sourcefile); jxl.sheet = Rwb.getsheet (0); int gcolumns = rs.getColumns (); 3. Cell [] getColumn (int column) Gets all cells of a column, returning a cell object array, example: jxl.workbook rwb = jxl .Workbook.getWorkbook (new file (sourcefile)); jxl.sheet = rwb.getsheet (0); cell [] cell = rs.getColumn (0); 4. Int getRows () Get the total line contained in the Sheet table Number, example: jxl.Workbook RWB = jxl.Workbook.getWorkbook (new file (sourcefile); jxl.sheet = rwb.getsheet (0); int gRows = rs.getrows (); 5. Cell [] getRow int ROW) Gets all cells of a certain line, returning the cell object array, an example: jxl.workbook rwb = jxl.Workbook.getWorkbook (new file (sourcefile); jxl.sheet = rwb.getsheet (0 Cell [] Cell = rs.getrow (0); 6. Cell getcell (int column, int) Gets the object reference to the specified cell, you need to pay attention to its two parameters, the first is the number of columns, The second is the number of lines, which is different from the usual rows, and the column combination is somewhat different. JXL.Workbook RWB = jxl.Workbook.getWorkbook (new file (sourcefile)); jxl.sheet = rwb.getsheet (0); cell cell = rs.getcell (0, 0); generate new Excel works below The code is mainly to introduce you how to generate a simple Excel worksheet, where the content of the cell is no modified (e.g., font, color, etc.), all of which are written as a string. (Full code See Excelwriting.java) Similar to reading Excel worksheets, first create a Workbook object using the factory method of the Workbook class, hereby pay attention, can only be provided by the API Method to create Workbook, not to use WritableWorkbook constructor because the constructor of class WritableWorkbook is protected by protected type. The sample code snippet is as follows:

Import java.io. *; import jxl. *; import jxl.write. *; ... ... ... try {// Build a Workbook object, read-only Workbook object // Method 1: Create a writable Excel workbook JXL. write.WritableWorkbook wwb = Workbook.createWorkbook (new File (targetfile)); // Method 2: WritableWorkbook written directly to the output stream / * OutputStream os = new FileOutputStream (targetfile); jxl.write.WritableWorkbook wwb = Workbook.createWorkbook (OS); * /} catch (Exception E) {E.PrintStackTrace ();} API provides two ways to process the writable output stream, one is to generate local files, if the file name does not have a full path If the default file is positioned in the current directory, if the file name comes with a full path, the generated Excel file is positioned in the corresponding directory; the other is to write the Excel object directly to the output stream, for example: The user accesses the web server through the browser. If the HTTP header is set, the browser automatically calls the client's Excel application to display dynamically generated Excel spreadsheets.

The next step is to create a worksheet, the method of creating a worksheet is almost the same as the method of creating a work, and the corresponding object is also obtained through the factory mode method. This method requires two parameters, one is the name of the worksheet, the other is Worksheets in the position of work, refer to the following code snippet: file: // Create an Excel worksheet jxl.write.writablesheet WS = wwb.createsheet ("Test Sheet 1", 0); "This pot is also supported The material is also ready, and it is possible to start the pot! ", Now you have to do it is just the Excel basic data type provided by the API, and you can add them to the worksheet. Refer to the following code segment: File : // 1. Add label object jxl.write.label labelc = new jxl.write.label (0, 0, "this is a label cell"); ws.addcell (labelc); // Add with font formatting For jxl.write.WritableFont wf = new jxl.write.WritableFont (WritableFont.TIMES, 18, WritableFont.BOLD, true); jxl.write.WritableCellFormat wcfF = new jxl.write.WritableCellFormat (wf); jxl.write. Label labelcf = new jxl.write.label (1, 0, "this is a label cell", ws.addcell (labelcf); // Add a font color formatting object jxl.write.writableFont WFC = New jxl.write.WritableFont (WritableFont.ARIAL, 10, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.RED); jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat (wfc); jxl. Write.label labelcfc = new jxl.write.label (1, 0, "this is a label cell", wcffc); ws.addcell (labelcf); // 2. Add Number object jxl.write.Number labeln = new jxl.write.Number (0, 1, 3.1415926); WS. Addcell (labeln); // Add Number object with formatting, jxl.write.Numberformat nf = new jxl.write.Numberformat ("#. ##"); jxl.write.writablecellformat wcfn = new jxl.write.writableCellFormat NF); jxl.write.number labelnf = new jxl.write.Number (1, 1, 3.1415926, ws.addcell (labelnf); // 3. Add Boolean object jxl.write.Boolean labelb = new jxl. Write.Boolean (0, 2, FALSE); WS.Addcell (labelb);

// 4. Add a DateTime object jxl.write.datetime labeldt = new jxl.write.datetime (0, 3, new java.util.date ()); ws.addcell (labeldt); // Add a DateFormat with formatting Object jxl.write.dateformat DF = new jxl.write.dateFormat ("DD MM YYYY HH: MM: SS"); jxl.write.writablecellformat wcfdf = new jxl.write.writableCellFormat (DF); jxl.write.datetime labeldtf = New jxl.write.datetime (1, 3, new java.util.date (), wcfdf); ws.addcell (labeldtf); there are two points to cause everyone to pay attention. The first point, when constructing the cell, the location of the cell in the worksheet has been determined. Once created, the location of the cell cannot be changed, although the content of the cell can be changed. In the second point, the positioning of the cell is the following regularity (COLUMN, ROW), and the subscript starts from 0, for example, A1 is stored in (0, 0), B1 is stored (1, 0) . Finally, don't forget to close the open Excel workmail object, to release the usage memory, see the following code snippet: file: // Write the EXEL worksheet Wwb.write (); // Close Excel work thin object Wwb.close ( ); This may have little difference with the operation of reading the Excel file, before closing the Excel object, you must first call the Write () method, because the previous operation is stored in the cache, so it is necessary to operate through this method. The content is saved in the file. If you turn off the Excel object first, you can only get an empty work. Copy, update Excel work thin Next briefly introduces how to update an existing work, mainly below, the first step is to construct a read-only Excel work, the second step is to use the Excel workbook that has been created Create a new writable Excel workbook, refer to the following code snippet: (full code See ExcelModifying.java) file: // Create a read-only Excel work thin object JXL.Workbook rw = jxl.Workbook.getWorkbook (New File (sourcefile)); // Create a writable Excel workmail object jxl.write.writableworkbook wwb = workbook.createworkbook (new file (targetfile), rw); // reads the first workpiece jxl.write. Writablesheet ws = wwb.getsheet (0); // Get the first cell object jxl.write.WritableCell wc = ws.getwritablecell (0, 0); // Determine the type of cell, make corresponding transformation IF ( Wc.gettype () == celltype.label) {Label L = (label) WC; L.SetString ("The value has been modified.");} // Write Excel object Wwb.write (); // Off The writable Excel object wwb.close (); // Close the read-only Excel object rw.close (); use this way to build an Excel object, which is complete because of the reason, because the above example is API Main application.

In order to improve performance, when reading a worksheet, some of the output information related to the data, all format information, such as: font, color, etc. are not processed, because our purpose is to get the value of row data, both There is no modification, nor does it affect the value of the value. The only unfavorable thing is that in memory will save both the same worksheet, so when the worksheet is large, it will occupy a considerable amount of memory, but now the size of memory is not a key factor. Once you have a writable worksheet object, we can update the cell object, where we do not have to call the ADD () method provided by the API, because the cell has been in the worksheet, so we only need To call the corresponding setxxxx () method, you can complete the update operation. Using the original formatted modification of the cells cannot be removed, we can also add new units to make the content of the cells in different forms. The newly generated worksheet object is writable. In addition to updating the original unit, you can add a new cell to a worksheet, which is exactly the same as the operation of Example 2. Finally, don't forget to call the Write () method, write the updated content into the file, then turn off the workmaking object, here there are two working thin objects to be turned off, one is read-only, and the other is writable. The following is a simple example of creating a matrix in an Excel form: import org.Apache.poi.hssf.usermodel. *; Import java.io.fileoutputstream;

// code run against the jakarta-poi-1.5.0-FINAL-20020506.jar.public class PoiTest {static public void main (String [] args) throws Exception {FileOutputStream fos = new FileOutputStream ( "foo.xls"); HSSFWORKBOOK WB = new hssfworkbook (); hssfsheet s = wb.createsheet (); wb.setsheetname (0, "matrix"); for (Short i = 0; i <50; i ) {hssfrow rot = S.Createrow (i ); for (short j = 0; j <50; j ) {hssfcell cell = row.createcell (j); cell.setcellValue (" i ", " j);}} wb.write (fos); Fos.close ();} This code first creates a Workbook, get a table, name, and then write into a 50X50 matrix. Finally output an Excel file called foo.xls, or even on the Apple Mac machine. The POI project is an exciting step of Java applications, providing users with new features of Windows document integration, allowing Java developers to easily expand their products.

转载请注明原文地址:https://www.9cbs.com/read-34577.html

New Post(0)