Department of java write excel file can be used jxl library, you can also use POI library, however, jxl library only supports low version excel2003, does not support a later version, can not be directly output file * .xlsx, * .xls file can only output In addition, the update is not frequent. So, now we use a POI library.
jxl library official website: http://jxl.sourceforge.net/
POI Introduction
To use the POI for Excel operation, we need to first look at Excel in two versions: one version is 97-2003 extension is ".xls"; one is the 2007 version of the extension is ".xlsx". For each POI jar package two versions need to import different operation classes are different.
HSSF: operation is .xls; XSSF: operation is .xlsx.
Regardless of the operation, the basic ideas are the same, first corresponds to an Excel file, then a sheet in the corresponding file, followed by a column in a row and operation of the line. Corresponding to the POI Package: File (webbook), sheet (sheet), row (Row) and the specific cell (cell).
Detailed operation please refer to the official website of the POI Excel (HSSF / XSSF) operation. In addition, there EasyPOI , functions and POI almost, Easypoi poi goal is not to replace, but to not understand the import and export of a quick completion of the various operations using poi Excel and word, and not see a lot of api can complete this work.
Here are my test case source.
1, add the lib file in the project required poi library (this test version poi-bin-4.1.2-20200217.zip) came in and added to the Build Path in the following chart:
2, project source code:
package com.reus; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelOperate { public static void main(String[] args) { String[][] data = { { "中文", "$1275.00" }, { "Pets", "$125.00" }, { "Electronics", "$2533.00" }, { "Mensware", "$497.00" } }; String[] headers = { "Department", "Daily Revenue" }; JFrame frame = new JFrame("JTable to Excel Hack"); DefaultTableModel model = new DefaultTableModel(data, headers); final JTable table = new JTable(model); JScrollPane scroll = new JScrollPane(table); default output to a local directory project//= "out.xlsx"; OutFullPath String = JButton exportButtonnew new the JButton ( "output"); // output Excel file exportButton.addActionListener ( new new the ActionListener () { public void the actionPerformed (the ActionEvent EVT) { the try { createExcel (Model, outFullPath); // output and create Excel } the catch (Exception EX) { System.out.println (ex.getMessage ()); ex.printStackTrace (); } } }); the JButton readButton = new new the JButton ( "read"); //Excel file reading, printing displayed in the console window readButton.addActionListener ( new new the ActionListener () { public void the actionPerformed (the ActionEvent EVT) { the try { the SimpleDateFormat SDF = new new the SimpleDateFormat ( "HH: mm: SS: the SS" ); the TimeZone T = sdf.getTimeZone (); t.setRawOffset ( 0 ); sdf.setTimeZone (T); Long the startTime = System.currentTimeMillis (); // for calculating the read data from the time-consuming excel file String fileName= "in.xlsx"; readExcel(fileName);// 读取Excel,xlsx后缀名的文件 Long endTime = System.currentTimeMillis(); System.out.println("用时:" + sdf.format(new Date(endTime - startTime))); } catch (Exception ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); } } }); JPanel bottomPanel=new JPanel(); bottomPanel.setLayout(new BorderLayout()); bottomPanel.add(exportButton, BorderLayout.NORTH); bottomPanel.add(readButton, BorderLayout.SOUTH); frame.getContentPane().add("Center", scroll); frame.getContentPane().add("South", bottomPanel); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } @SuppressWarnings({ "resource"}) public static void readExcel(String strPath) throws{IOException // configured XSSFWorkbook objects, strPath incoming file path XSSFWorkbook XWB = new new XSSFWorkbook (strPath); // read the contents of the first table XSSFSheet Sheet xwb.getSheetAt = (0); // 0 represents a table / / definitions Row, Cell XSSFRow Row; XSSFCell Cell; // cycle of the output table contents for ( int I = sheet.getFirstRowNum (); I <sheet.getPhysicalNumberOfRows (); I ++ ) { Row = sheet.getRow (I); for ( int J = row.getFirstCellNum (); J <row.getPhysicalNumberOfCells (); J ++ ) { RET String = "" ; Cell = row.getCell (J); RET = getCellValueByCell (Cell); of System.out.print (RET + "\ T" ); } System.out.println ( "" ); } } / / get a cell value of each type, the type of return string public static string getCellValueByCell (the cell cell) { // determines whether an empty string is null or iF (cell == null || cell.toString (). TRIM (). the equals ( "" )) { return ""; } String CellValue = "" ; the CellType celltype = cell.getCellType (); Switch (celltype) { Case the NUMERIC: // the enum constant before the redundancy information can be removed by the compiler Short the format = cell.getCellStyle (). getDataFormat (); IF (DateUtil.isCellDateFormatted (the Cell)) { // Note: DateUtil.isCellDateFormatted () method on the "January 18, 2019," the date of this format, the judge will have problems, need to be addressed separately SimpleDateFormat sdf = null ; // System.out.println ( "cell.getCellStyle () getDataFormat () =." + cell.getCellStyle () getDataFormat ().); IF(|| 20 is the format the format == == 32 ) { SDF = new new the SimpleDateFormat ( "HH: mm" ); } the else IF (the format == || 14 || 31 is the format the format == == == 57 is the format || 58 ) { // handle custom date format: m d May 1999 (determined by the format of the cell id solution, id value is 58) SDF = new new the SimpleDateFormat ( "the MM-dd-YYYY" ); Double value = cell. getNumericCellValue (); a Date DATE = org.apache.poi.ss.usermodel.DateUtil.getJavaDate (value); CellValue = sdf.format (DATE); }else {// 日期 sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } try { cellValue = sdf.format(cell.getDateCellValue());// 日期 } catch (Exception e) { try { throw new Exception("exception on get date data !".concat(e.toString())); } catch (Exception e1) { e1.printStackTrace(); } } The finally { SDF = null ; } } the else { BigDecimal BD = new new BigDecimal (cell.getNumericCellValue ()); CellValue = bd.toPlainString (); // value of such packaging with BigDecimal reacquisition plainString, can be prevented to obtain a count value SCIENCES } BREAK ; Case sTRING: // string CellValue = cell.getStringCellValue (); BREAK ; Case BOOLEAN: Boolean// = cell.getBooleanCellValue CellValue () + "" ; BREAK ; Case the FORMULA: // formula { // CellValue cell.getCellFormula = (); // read the formula in the cell cellValue = String.valueOf (cell.getNumericCellValue () ); // read the value in the cell } BREAK ; Case bLANK: // null CellValue = "" ; BREAK ; Case ERROR: // fault CellValue = "ERROR of vALUE" ; break; default: cellValue = "UNKNOW VALUE"; break; } return cellValue; } /** * 用户列表导出,生成Excel */ private static void createExcel(TableModel model, String outFileFullPath) { XSSFWorkbook userListExcel = createUserListExcel(model); try { // 输出成文件 FileOutputStream outputStream = new FileOutputStream(new File(outFileFullPath)); userListExcel.write (the outputStream); outputStream.close (); } the catch (Exception E) { e.printStackTrace (); } } / ** * Create Excel * / Private static XSSFWorkbook createUserListExcel (the TableModel Model) { // 1. Create HSSFWorkbook, a corresponding one of Excel HSSFWorkbook file XSSFWorkbook WB = new new XSSFWorkbook (); // 2. Add a sheet in the workbook, the corresponding sheet Excel file XSSFSheet = wb.createSheet sheet ( "Sheet1" ); // 3. set the header, i.e., each column the column names XSSFRow row = sheet.createRow (0); // create the first line for (int I = 0; I <model.getColumnCount (); I ++ ) { row.createCell (I) .setCellValue (model.getColumnName (I)); // to column write data, to create a cell, to write the column name } // write formal data for ( int I =. 1; I <= model.getRowCount (); I ++) { // first index. Since the first line has been accounted for in the table heading, the index data from a start Chang Row = sheet.createRow (I); // create a true line for storing data for ( int J = 0; J <model.getColumnCount (); J ++) { // the column index row.createCell (J) .setCellValue (model.getValueAt (I. 1- , J) .toString ()); sheet.autoSizeColumn ( . 1, to true ); } } return wb; } }
3, operating results
Main interface:
Output:
Enter the result:
Description:
The above and out.xlsx in.xlsx in the project are the current directory, as shown below:
references:
1、http://www.zuidaima.com/code/file/2737946451706880.htm?dir=/2737946451706880.java
2, the JAVA implemented database data import / export to Excel (POI)
3, the Java using POI to export data into Excel
. 5, Java data types excel in reading date by the date poi or custom type