POI导入导出



package com.gxcz.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
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.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.gxcz.xuhui.investment.model.BonusDetail;
import com.gxcz.xuhui.investment.model.CompleteSubscribeRecord;
import com.gxcz.xuhui.investment.model.dto.BonusDetailDTO;
import com.gxcz.xuhui.investment.model.dto.CompleteSubscribeRecordDTO;

public class ExcelUtil {

 private static final int version2003 = 2003;

    private static final int version2007 = 2007;  //2007以上版本

    private static int version = version2003;

    private static Workbook wb = null;

    private static Sheet sheet=null;

    private static Cell cell = null;

    private static Row row=null;
   
    /**
     *  用于导入
     * 获取excel 的数组
     * @param excelFilePath
     * @return
     * @throws IOException
     */
    private static String[][] getExcelStr(CommonsMultipartFile file,String fileName,int beginRow) throws IOException{
       //判断类型 2003,2007
        if (fileName.endsWith(".xls")){
          version = version2003;
        }  else if (fileName.endsWith(".xlsx")){
          version = version2007;
        }

     InputStream stream=null;
    if (version == version2003) {
        stream =  file.getInputStream();
         wb = (Workbook) new HSSFWorkbook(stream);
     } else if (version == version2007) {
         wb = (Workbook) new XSSFWorkbook(file.getInputStream());
     }

        sheet = wb.getSheetAt(0);
       // 行数(从0开始,相当于最后一行的索引),列数

        int count_row=sheet.getLastRowNum();
        for (int i = 0; i < count_row; i++) {
         row=sheet.getRow(i+beginRow); //年模板,从第三行开始读
         cell=row.getCell(0);
         if(cell.getStringCellValue() == null || cell.getStringCellValue().equals("")){
          count_row = i+beginRow;
          break;
         }
        }
        int count_cell=sheet.getRow(0).getPhysicalNumberOfCells();
        String[][] str=new String[count_row][count_cell];
        for (int i = 0; i < count_row; i++) {
               for (int j = 0; j < count_cell; j++) {
                      row=sheet.getRow(i+beginRow);
                      cell=row.getCell(j);
                     int type = cell.getCellType(); // 得到单元格数据类型
                     String k = "";
                     if(type ==Cell.CELL_TYPE_STRING){
                      if(cell.getStringCellValue() == null){
                       break;
                      }
                     }
                     switch (type) { // 判断数据类型
                     case Cell.CELL_TYPE_NUMERIC:
                         if(DateUtil.isCellDateFormatted(cell)){
                                  k = new DataFormatter().formatRawCellContents(cell.getNumericCellValue(), 0, "yyyy-mm-dd");//
                          }else{
                                   k=cell.getNumericCellValue()+"";  
                           }
                       break;
               case Cell.CELL_TYPE_STRING:
                           k = cell.getStringCellValue();
                           break;
               case Cell.CELL_TYPE_FORMULA:
                      k = cell.getCellFormula();
                      break;
                       case Cell.CELL_TYPE_BLANK:
                                         k = "";
                                         break;
                        case Cell.CELL_TYPE_BOOLEAN:
                                         k = cell.getBooleanCellValue() + "";
                                         break;
                        case Cell.CELL_TYPE_ERROR:
                                         k = cell.getErrorCellValue() + "";
                                         break;
                              default:
                                             break;
                                    }
                      str[i][j]=k;
               }
        }
        cell=null;
        row=null;
        sheet=null;
        wb=null;
     return str;
    }
 
  /**
     * 导出文件的方法
     * @param wb
     * @param srcFilePath
     * @param response
     */
    private static void exportFile(String filename,Workbook wb,String srcFilePath, HttpServletResponse response){
//     File file = new File(srcFilePath); 
//   // 取得文件名。 
//  String filename = file.getName(); 
  response.setContentType("application/vnd.ms-excel; charset=utf-8");
  response.setHeader("Content-Disposition","attachment;filename="+filename);
  try {
    OutputStream out = response.getOutputStream();
    wb.write(out);
    out.close(); 
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
    }
    
 
 
   
   /**
    * 导入Excel
    * @param excelFilePath
    * @param userId
    * @param projectId
    * @return
    * @throws IOException
 * @throws ParseException
    */
 public static List readBonusDetailExcel(CommonsMultipartFile file,String fileName) throws    IOException, ParseException {
   String[][] str = getExcelStr(file,fileName,2); //读取excel
        List list = new ArrayList();
        for (int k = 0; k < str.length; k++) {
               String[] temp_str=str[k];
               if(temp_str[0].equals("")){
                break;
               }
               BonusDetail bonusDetail=new BonusDetail();
               for (int s = 0; s < temp_str.length; s++) {
             String number = temp_str[s];//编码
               ^^

               ^^
                list.add(bonusDetail);
                    break;
               }
        }
        return list;
   }
 
 /**
     * 导出 Excel
     * @param srcFilePath
     * @param newFilePath
     * @param data
     * @param response
     */
    public static void writeBonusDetailExcel(String srcFilePath,String newFilePath,List data, HttpServletResponse response){
     try{
       InputStream in = new FileInputStream(srcFilePath); 
          //读模板文件
             wb = (Workbook)new XSSFWorkbook(in);
             sheet = wb.getSheetAt(0);
             sheet.getRow(1).getCell(0).setCellValue("编码");
             if(data != null && data.size() > 0){
              for(int i=0;i                       row=sheet.getRow(i+2);
                     ^^ ^^^^^^^^^^^^
                }
             }
             String filename = "fenhong-"+BaseUtil.formatDate(new Date(), "yyyyMMddHHmmss");
             exportFile(filename,wb,srcFilePath,response);
            
     }catch(FileNotFoundException e){
      e.printStackTrace();
     }catch(IOException e){
      e.printStackTrace();
     }
    }
 
}

你可能感兴趣的:(基础开发)