package com.ag.secp.platform.office.excel;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.*;
import java.util.List;

/**
 * Created by Administrator on 2018/1/7.
 */
public class ExpPoiSimExcel {

    /**
     * 导出excel文档
     * @param data
     * @param isFilePath
     * @param osFilePath
     * @return
     * @throws Exception
     */
    public static  String expExcel(List data,String isFilePath,String osFilePath)throws Exception{
        Workbook wb=ExpPoiSimExcel.fillExcelDataWithTemplate(data,isFilePath);
        ExpPoiSimExcel.export( wb,osFilePath);
        return osFilePath;
    }

    /**
     * 循环处理数据
     * @param data
     * @param isFilePath
     * @return
     * @throws Exception
     */
    public static Workbook fillExcelDataWithTemplate(List data, String isFilePath)throws Exception{
        InputStream is = new FileInputStream(isFilePath);
        POIFSFileSystem fs=new POIFSFileSystem(is);
        Workbook wb=new HSSFWorkbook(fs);
        Sheet sheet=wb.getSheetAt(0);
        //得到标题行列数
        int cellNums=sheet.getRow(1).getLastCellNum();
        int rowIndex=2;
        for (int i= 0; data !=null && i < data.size();i++) {
            Row row = sheet.createRow(rowIndex++);
            List slist = (List) data.get(i);
            for (int j = 0; j < cellNums; j++) {
                row.createCell(j).setCellValue(String.valueOf(slist.get(j)));
            }
        }
        return wb;
    }

    /**
     * 输出文件
     * @param wb
     * @param osFileName
     * @throws Exception
     */
    public static void export(Workbook wb, String osFileName)throws Exception{
        File outFile = new File(osFileName);
        OutputStream out= new FileOutputStream(outFile);
        wb.write(out);
        out.flush();
        out.close();
    }

//    public static void main(String[] args) {
//        try {
//            List data = new ArrayList();
//            TStudent tStudent = new TStudent();
//            tStudent.setName("1");
//            tStudent.setSex("1");
//            tStudent.setAge((short) 10);
//            tStudent.setGradeCod("G101");
//            data.add(tStudent);
//            String isFilePath = "D:\\test\\student.xls";
//            String osFilePath = "D:\\test\\s" + System.currentTimeMillis() + ".xls";
//            ExpPoiSimExcel.expExcel(data,isFilePath,osFilePath);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}
