Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Linux \ Apache POI Excel Document Processing     - Spark SQL job of a lifetime (Server)

- Ubuntu 14.04 and derivative version of the user on how to install cURL 7.37.1 (Linux)

- To install Python-Pip and Fabric under CentOS / Ubuntu (Linux)

- Ceph Source Analysis: Network Module (Server)

- Ubuntu iptables prevent IP attacks (Linux)

- CentOS 7.0 Automatic installation CD-ROM production Comments (Linux)

- Ubuntu 12.04 LTS installation configuration JDK1.6.0_45 (Linux)

- Git uses a standard process (Linux)

- Use small network command to check whether PC Security (Linux)

- Oracle 11g RAC manually playing GI PSU patch (11.2.0.4.8) (Database)

- How to install and use the Snort in Ubuntu 15.04 (Linux)

- Emacs install clojure development environment (Linux)

- Install RAID 6 (Striping double distributed parity) (Linux)

- SSH without password Definitive Guide (Linux)

- Linux (Debian) install software, missing dynamic link libraries .so (Linux)

- The sublime into IDE (Linux)

- Install Java on RHEL6 (Linux)

- Tmux create the perfect terminal management tool under CentOS (Linux)

- Installation Mesos + Marathon + Zookeeper under CentOS 7 (Server)

- High-performance JavaScript DOM programming (Programming)

 
         
  Apache POI Excel Document Processing
     
  Add Date : 2018-11-21      
         
       
         
  Currently popular treatment excel document, there are two general ways, namely POI and JXL. Heavyweight POI advantages and disadvantages: suitable for excel document details a relatively professional requirements, such as using formulas, macros and other advanced features; drawback is that the operation is relatively cumbersome, non-pure java prepared rack package, cross-platform needs to be strengthened. Lightweight JXL disadvantages: Jxl pure javaAPI, excellent cross-platform, the operation is relatively simple; drawback is that does not support some of the advanced features excel document, but to meet the daily needs. Here we introduce the basic use of the POI.

1. First, import the relevant frame package

Also note that this version of the JDK you what development projects is to download different versions according to the corresponding POI JDK version.

2. Operation ExcelReader helper class can handle xls and xlsx files, readExcelTitle (InputStream is) Reads the file header, which is the first line of the file, readExcelContent (InputStream is) method to read the contents of the file:

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
  
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
  
/ **
 * Operation Excel spreadsheet functionality class
 * /
public class ExcelReader {
    private static DecimalFormat df = new DecimalFormat ( "0");
    private final static Logger log = Logger.getLogger (ExcelReader.class);
    private Workbook wb = null;
    private Sheet sheet = null;
    private Row row = null;
  
    / **
    * Read the contents of an Excel spreadsheet header
    * @param InputStream
    * @return String array header content
    * @throws IOException
    * /
    public String [] readExcelTitle (InputStream is) throws Exception {
        try {
            wb = WorkbookFactory.create (is);
        } Catch (IOException e) {
            log.error ( "read the contents of Excel spreadsheet header abnormal", e);
            throw e;
        }
        sheet = wb.getSheetAt (0);
        row = sheet.getRow (0);
        The total number of columns // heading
        int colNum = row.getPhysicalNumberOfCells ();
        String [] title = new String [colNum];
        for (int i = 0; i             title [i] = getCellFormatValue (row.getCell (i));
        }
        log.info ( "read the contents of the complete Excel table header");
        return title;
    }
  
    / **
    * Read Excel data content
    * @param InputStream
    * @return Map Map object that contains the cell data content
    * @throws IOException
    * /
    public Map readExcelContent (InputStream is) throws Exception {
        Map content = new LinkedHashMap ();
        String str = "";
        try {
            wb = WorkbookFactory.create (is);
        } Catch (IOException e) {
            log.error ( "read Excel data content", e);
            throw e;
        }
        sheet = wb.getSheetAt (0);
        // Get the total number of rows
        int rowNum = sheet.getLastRowNum ();
        row = sheet.getRow (0);
        int colNum = row.getPhysicalNumberOfCells ();
        // Body content should start from the second row, first row header title
        for (int i = 1; i <= rowNum; i ++) {
            row = sheet.getRow (i);
            int j = 0;
            while (j                 // The data contents of each cell with a "-" separated, String class replace when needed for future use () method to restore data
                // You can also set the data to each cell in a javabean attribute, then you need to create a javabean
                // Str + = getStringCellValue (row.getCell ((short) j)). Trim () +
                // "-";
                if (row! = null) {
                    . Str + = getCellFormatValue (row.getCell (j)) trim () + ",";
                } Else {
                    str + = "" + ",";
                }
                j ++;
            }
            content.put (i, str.substring (0, str.length () - 1));
            str = "";
        }
        log.info ( "read Excel data content complete");
        return content;
    }
  
    / **
    * Set the type of data based on Cell
    * @param Cell
    * @return
    * /
    private String getCellFormatValue (Cell cell) {
        String cellvalue = "";
        if (cell! = null) {
            Analyzing the current // Type Cell
            switch (cell.getCellType ()) {
            // If the current Type Cell is NUMERIC
            case Cell.CELL_TYPE_NUMERIC:
            case Cell.CELL_TYPE_FORMULA: {
                // Determine whether the current cell to Date
                if (DateUtil.isCellDateFormatted (cell)) {
                    // If the Date type is converted to a Data Format
  
                    // Method 1: The data format is like this with every minute of the time: 2015-12-18 0:00:00
                    // Cellvalue = cell.getDateCellValue () toLocaleString ().;
  
                    // Method 2: data format is like this when every minute without tape: 2011-10-12
                    Date date = cell.getDateCellValue ();
                    SimpleDateFormat sdf = new SimpleDateFormat ( "yyyy-MM-dd");
                    cellvalue = sdf.format (date);
  
                }
                // If it is a pure digital
                else {
                    // Get the current value of the Cell
                    cellvalue = String.valueOf (df.format (cell.getNumericCellValue ()));
                }
                break;
            }
            // If the current Type Cell is STRIN
            case Cell.CELL_TYPE_STRING:
                // Get the current Cell strings
                cellvalue = cell.getRichStringCellValue () getString ().;
                break;
            // Default value of Cell
            default:
                cellvalue = "";
            }
        } Else {
            cellvalue = "";
        }
        return cellvalue;
  
    }
}

Simple example code, the actual use of exception handling mechanism should be added:
12345678910111213 FileInputStream is = new FileInputStream (file);
    ExcelReader excelReader = new ExcelReader ();
    String [] title = excelReader.readExcelTitle (is); // read the file title (non-file name, but the first line of the file)
    for (String str: title) {
    System.out.println (str);
    }
    is.close ();
    is = new FileInputStream (file);
    Map map = excelReader.readExcelContent (is); // read the contents of the file
    for (int i = 1; i <= map.size (); i ++) {
        System.out.println (map.get (i));
    }
    is.close ();
     
         
       
         
  More:      
 
- Via Twitter how open source library to be used anywhere Emoji emoticons (Linux)
- Using the Linux folder wc statistics number of lines of code for all files (including subdirectories) (Linux)
- MongoDB data replication and data slices (Database)
- Four IDS intrusion detection tool under Linux environment (Linux)
- Linux, modify / etc / profile file (Linux)
- The istgt PSD on ported to Mac OS X (Linux)
- The hash function under OpenSSL (Linux)
- Shuffle Process Arrangement in MapReduce (Server)
- SQL Server 2008 database synchronization Notes (Database)
- ASM Disk Space Check (Database)
- Use Python automatically cleared Android Engineering excess resources (Programming)
- CentOS 7 open ports (Linux)
- grep command Series: grep command to search for multiple words (Linux)
- To delete the directory and all specified files under the Mac (Linux)
- Using iptables achieve NAT (Linux)
- CentOS 7 Test Marathon start Docker container (Server)
- How to network to share files between Windows, MAC and Linux (Linux)
- RM Environment Database RMAN Backup Strategy Formulation (Database)
- Variables Python variables (Programming)
- Compare Dalvik virtual machine and the JVM (Linux)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.