Java Operations Excel Tool class sharing

Source: Internet
Author: User

import java.io.bytearrayoutputstream;import java.io.ioexception;import java.io.outputstream; Import java.text.decimalformat;import java.text.simpledateformat;import java.util.date;import  java.util.HashMap;import org.apache.poi.hssf.usermodel.HSSFCell;import  org.apache.poi.hssf.usermodel.hssfdateutil;import org.apache.poi.hssf.usermodel.hssfformulaevaluator; 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.ss.usermodel.Cell;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.xssf.usermodel.xssfworkbook;import  org.springframework.web.multipart.multipartfile;public class exceldatautil {     public string getfilename (Multipartfile file) &NBSP;{&Nbsp;       return  (String)  file.getoriginalfilename ();     }    public string[][] getexceldata (MultipartFile file,  int columnnumber)             throws  Exception {        String[][] arr = null;         Workbook wb = null;         try {            wb  = new hssfworkbook (File.getinputstream ());//2003         } catch  (exception e)  {             wb = new xssfworkbook (File.getinputstream ());//2007         }        int sheetnum = wb.getnumberofsheets ();         for  (int i = 0; i < sheetnum; i++)  {             Sheet childSheet =  Wb.getsheetat (i);            int rownum  = childsheet.getphysicalnumberofrows ();             for  (int j = 0; j < rownum; j++)  {                 Row row =  Childsheet.getrow (j);                 int cellNum = columnNumber + 1;                 if  (j == 0)                      arr = new String[rowNum][cellNum];                 for  (int  k = 0; k < cellnum; k++)  {                     cell cell =  row.getcell (k);                     arr[j][k] = parseexcel (cell);                 }             }        }         return arr;    }            public  Static string getsheetname (Multipartfile file)              throws exception {        workbook  wb = null;        try {             wb = new hssfworkbook (File.getInputStream ());// 2003        } catch  (exception e)  {             wb = new xssfworkbook ( File.getinputstream ());//2007        }         return wb.getsheetname (0);    }                     public hashmap<string, hashmap<string,  String[][]>> getexcelmapdata (             multipartfile file, int columnnumber)  throws Exception {         hashmap<string, hashmap<string, string[][]>> maps  = new HashMap<String, HashMap<String, String[][]>> ();         hashmap<string, string[][]> mapda = new hashmap <String, String[][]> (        string filename =);  file.getoriginalfilename ();         string modelyear= "";         if (Filename.lastindexof ("_")!=-1) {          &nbSp;  modelyear = filename.substring ((Filename.lastindexof ("_")-4),                      ( Filename.lastindexof ("_")));        }             String[][] arr = null;         workbook wb = null;        try {             wb = new hssfworkbook ( File.getinputstream (),  true);//2003        } catch  ( Exception e)  {            wb =  new xssfworkbook (File.getinputstream ());//2007        }       &nbsP; int sheetnum = wb.getnumberofsheets ();         for  (int i = 0; i < sheetnum; i++)  {             sheet childsheet = wb.getsheetat (i);             String ModelType =  Wb.getsheetname (i);             int rownum  = childsheet.getphysicalnumberofrows ();             for  (int j = 0; j < rownum; j++)  {                 Row row =  Childsheet.getrow (j);                 if (row!=null) {  &nbsP;                 int  cellNum = columnNumber + 1;                     if  (j == 0)                           arr = new String[rowNum][cellNum];                     for  (int k =  0; k < cellnum; k++)  {                         Cell cell  = row.getcell (k);                   &nbsP;     arr[j][k] = parseexcel (cell);                     }                 }                              }            mapda.put ( Modeltype, arr);        }         maps.put (MODELYEAR,&NBSP;MAPDA);        return maps;     }        /**     *  DecimalFormat to avoid the E-annotation for big double      */     private static decimalformat decimalformat = new decimalformat ("#.# ##### ");     private string parseexcel (Cell cell)  {         if  (cell == null)              return  "";         string result  = new string ();        switch  (Cell.getCellType () )  {        case HSSFCell.CELL_TYPE_NUMERIC://  number Types             if  ( hssfdateutil.iscelldateformatted (cell)  {//  process date format,   time format                  SimpleDateFormat sdf = null;           &Nbsp;     sdf = new simpledateformat ("Yyyy-MM-dd HH:mm:ss");                 date date  = cell.getdatecellvalue ();                 result = sdf.format (date);             } else {                 double va = cell.getnumericcellvalue ();                 if  (va ==  (int)  va )//  remove the ". 0" after the numeric type                      result = string.valueof ((int)  va);                 else//                     result = string.valueof (VA);  if the double value is too big, it will be displayed  in e-notation                     result = decimalformat.format (VA);             }             Break;            case hssfcell.cell_type_ Formula:            // cell.getcellformula ();             try {         &Nbsp;       result = string.valueof (Cell.getNumericCellValue ());             } catch  ( Illegalstateexception e)  {                 result = string.valueof (Cell.getrichstringcellvalue ());             }             break;        case hssfcell.cell_type_string://  string type             result =  Cell.getrichstringcellvalue (). toString ();             break;        case HSSFCell.CELL_TYPE_BLANK:             result =  "";        default:             result =  "";             break;        }         return result;    }             public static void exportexcels (String fileName, String[][] excles, outputstream os)  throws IOException {         hssfworkbook wb = new hssfworkbook ();         hssfsheet sheet = wb.createsheet ("New sheet");         int rows = 0;        for ( String[] cells&nbsP;: excles) {            hssfrow row  = sheet.createrow (rows++);             Int cols = 0;            for (String  cellvalue : cells) {                 hssfcell cell = row.createcell (cols++);                 cell.setcellvalue (CellValue);             }        }         wb.write (OS);    }     Public static  byte[] exportexcels (string[][] excles)  throws IOException  {   &nBsp;    hssfworkbook wb = new hssfworkbook ();         bytearrayoutputstream os = new bytearrayoutputstream ();         hssfsheet sheet = wb.createsheet ("New sheet");         int rows = 0;         for (string[] cells : excles) {             hssfrow row = sheet.createrow (rows++);             int cols = 0;             for (string cellvalue : cells) {                 HSSFCell cell =  Row.createcell (cols++);                cell.setcellvalue (CellValue);             }         }        wb.write (OS);         return os.tobytearray ();     }}


Java Operations Excel Tool class sharing

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.