Read and write EXCEL files using JAVA

Download addresshttp ://download.csdn.net/detail/u010634066/8302683Download   directly


First download the poi package and jxl package


Read part:

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;


/**============================================================
 * Copyright:
 * Bag:
 * Modification record:
 * Date author content
 * =============================================================
 * 2014-12-25 shirenchuang        
 * ============================================================*/

/**
 * @author shirenchuang
 *
 */
public class ReadExecl {

    /*private String fileUrl;
   
    public ReadExecl(String fileUrl) {
        // TODO Auto-generated constructor stub
        this.fileUrl = fileUrl;
    }*/
   // File file = new File(fileUrl);
    
    /**

     * Read the content of Excel, the first-dimensional array stores the value of the column in a row, and the two-dimensional array stores how many rows

     * @param file read data source Excel

     * @param ignoreRows The number of rows to ignore when reading data, metaphor that the number of rows that do not need to be read in the row header is 1

     * @return the content of the data in Excel read out

     * @throws FileNotFoundException

     * @throws IOException

     */
    
    public static List<String[][]> getData(File file,int ignoreRows) throws IOException{
        //return the data of all worksheets
        List<String[][]> result = new ArrayList<String[][]>();
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
        POIFSFileSystem  fs = new POIFSFileSystem(in);
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFCell cell = null;
        wb.getNumberOfSheets();
        // multiple worksheets
        for(int i=0;i<wb.getNumberOfSheets();i++){
            // get worksheet
            HSSFSheet hf = wb.getSheetAt(i);
            //The data of a worksheet is squeezed to add 1. For example, execl plus the column name of the first row is a total of 66, but getLastRowNum() is 65, and the list is also counted
            String[][] rowResult = new String[hf.getLastRowNum()+1][7];
            //Multiple rows per sheet
            for(int rownumber = ignoreRows; rownumber<=hf.getLastRowNum();rownumber++){
                
                
                //The number of rows of the obtained row is uncertain. If there is a space after that row, the space column may be ignored
                HSSFRow row = hf.getRow(rownumber);
                if (row == null) {
                    continue;
                }
                // data for one row
                String[] colResult = new String[row.getLastCellNum()];
                // get multiple columns of a row
                /**
                 * There is a problem here that row.getLastCellNum() is inaccurate in some cases  
                 * Example: EXECL has a total of 7 columns of data but in fact some of the last few columns are empty, it will not count the empty columns into the column value by default;
                 * The error caused is that the column value that will be useful when you call the write method will be wrong;
                 *
                 */
                for(short colnumber = 0;colnumber<row.getLastCellNum();colnumber++){
                        String value="";
                    cell=row.getCell(colnumber);
                    //replace the cell type
                    if(cell!=null){
                        cell.setEncoding(HSSFCell.ENCODING_UTF_16);
                        switch(cell.getCellType()){
                        case HSSFCell.CELL_TYPE_STRING:
                            value = cell.getStringCellValue();
                            break;
                        case HSSFCell.CELL_TYPE_NUMERIC:
                            if (HSSFDateUtil.isCellDateFormatted(cell)) {

                                Date date = cell.getDateCellValue();

                                if (date != null) {

                                    value = new SimpleDateFormat("yyyy-MM-dd")

                                           .format(date);

                                } else {

                                    value = "";

                                }

                             } else {

                                value = new DecimalFormat("0").format(cell

                                       .getNumericCellValue());

                             }

                             break;
                        case HSSFCell.CELL_TYPE_FORMULA:
                         // No value if the data is generated for the formula when importing

                            if (!cell.getStringCellValue().equals("")) {

                               value = cell.getStringCellValue();

                            } else {

                               value = cell.getNumericCellValue() + "";

                            }

                            break;
                      
                        case HSSFCell.CELL_TYPE_BLANK:

                            break;

                        case HSSFCell.CELL_TYPE_ERROR:

                            value = "";

                            break;

                        case HSSFCell.CELL_TYPE_BOOLEAN:

                            value = (cell.getBooleanCellValue() == true ? "Y"

                                   : "N");

                            break;

                        default:

                            value = "";
                        }//switch
                        
                    }//if
                    if (colnumber == 0 && value.trim().equals("")) {
                       // break;
                     }
                    
                    colResult[colnumber]=rightTrim(value);
                }//for()列
                rowResult[rownumber]=colResult;
            }//for() 行
            if(rowResult!=null)
            result.add(rowResult);
        }//for worksheet
        in.close();
        
        return result;
    }
    
    
    /**

     * remove spaces from the right of the string

     * @param str String to process

     * @return the processed string

     */

     public static String rightTrim(String str) {

       if (str == null) {

           return "";

       }

       int length = str.length();

       for (int i = length - 1; i >= 0; i--) {

           if (str.charAt(i) != 0x20) {

              break;

           }

           length--;

       }

       return str.substring(0, length);

    }
    
}

write section

import java.io.File;
import java.io.IOException;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;



/**============================================================
 * Copyright: Yuanheng Communication Copyright (c) 2002 - 2012
 * Bag:
 * Modification record:
 * Date author content
 * =============================================================
 * 2014-12-25 shirenchuang        
 * ============================================================*/

/**
 * @author shirenchuang
 *
 */
public class WriterExecl {
    private static String writeUrl ="";
    public String getWriteUrl() {
        return writeUrl;
    }


    public void setWriteUrl(String writeUrl) {
        this.writeUrl = writeUrl;
    }


    public WriterExecl(String writeUrl ) {
        // TODO Auto-generated constructor stub
        this.writeUrl= writeUrl;
    }
    
    
    /**
     *  
     * This is simply writing an EXCEL table
     * **/  
    public static void writeEx(int row,String[][] data){  
        
        WritableWorkbook wwb = null;     
        Label label = null;     
        String file =writeUrl;  
        try {     
            // Create a writable workbook object     
           
            wwb = Workbook.createWorkbook(new File(file));     
            if (wwb != null) {     
                // Create a writable worksheet in the workbook, the first parameter is the worksheet name, and the second parameter is the location of the worksheet   
                WritableSheet ws = wwb.createSheet("test", 0);     
                if (ws != null) {     
                    /* add table structure */    
                    // Row     
                    for (int i=0;i<row;i++) {     
                        // List     
                        for (int j=0;j<data[i].length;j++) {     
                            // There are three parameters in the Label constructor, the first is the column, the second is the row, and the third is the content of the cell filled  
                            
                            label = new Label(j, i,data[i][j] );     
                            // Add the cell where the data is written to the worksheet     
                            ws.addCell(label);     
                        }     
                    }     
                    // write to file from memory     
                    wwb.write();     
                }     
                System.out.println("The path is: " + file + " the workbook write data successfully!");     
            }     
        } catch (Exception e) {     
            System.out.println(e.getMessage());     
        } finally {     
            try {   
                wwb.close();  
            } catch (WriteException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace ();  
            } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace ();  
            }     
        }     
    }  
}

Main method:


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;




public class main {

    public static void main(String[] args) throws IOException{
        ReadExecl re = new ReadExecl();
        File file = new File("C:/Users/Administrator/Desktop/test.xls");
        WriterExecl we = new WriterExecl("C:/Users/Administrator/Desktop/Quzhou User Table.xls");
        List<String[][]> result = new ArrayList<String[][]>();
        // do not ignore lines starting at 0
        result =  re.getData(file, 0);
        // how many lines are there
        int row = result.get(0).length;

         //Writing the incoming parameter row without passing the column column is uncertain
        we.writeEx(row,result.get(0));
       
    }
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325895681&siteId=291194637