JAVA使用poi进行EXCEL模板导入导出,XSSFCell数据类型

折腾了好久,终于结束了,算是一个模板导入的通用类呢吧;上代码:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.util.HashMap;

import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFDataFormat;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thinkgem.jeesite.common.utils.Encodes;
import com.thinkgem.jeesite.common.utils.StringUtils;

    /**
     * 导出EXCEL账套(使用模板导出)
     * @author Sunck
     *
     */

public class Exxx {

    private static Logger log = LoggerFactory.getLogger(ExportExcel.class);

    private XSSFWorkbook workbook;

    private XSSFSheet sheet;

    private XSSFRow row;//行对象

    private int rowNum;//待插入行号

    private int rownum;//当前行号

    private FileOutputStream fos;


    public Map<String, String> map = new HashMap<String, String>();//用于模板固定字符替换


    public Exxx(String url, int rowNum) {
        File file = new File(url);
        String realPath = ("H://uploadfile");
        String newFileName = System.currentTimeMillis() + ".xlsx";
        // 判断路径是否存在
        File dir = new File(realPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        // 写入到新的excel
        File newFile = new File(realPath, newFileName);
            try {
                newFile.createNewFile();
                // 写数据
                fileChannelCopy(file, newFile);
                InputStream io = new FileInputStream(newFile);
                this.workbook = new XSSFWorkbook(io);// 创建workbook,
                this.sheet = workbook.getSheetAt(0);//获取工作表(1)
                if(sheet!=null) {
                    this.fos = new FileOutputStream(newFile);
                }else {
                    log.debug("Write error: ["+row.getRowNum()+"] 数据为空");
                }
                //检测是否有数据,因为是走的模板所以不需要
                row = sheet.getRow(5);
                if (row == null) {
                    row = sheet.createRow(5);
                }
                XSSFCell cell = row.getCell(1);
                if (cell == null) {
                    cell = row.createCell(1);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            this.rowNum = rowNum;
    }

    /**
     * 
     * @param m当前插入行数
     * @return Row对象
     */
    public void addRow(int m) {
        sheet.shiftRows((int)m+this.rowNum, sheet.getLastRowNum(), 1);
        row =  sheet.createRow((int)m+this.rowNum);
    }






    /**
     * 加入单元格(文字)
     * @param value 字面的值
     * @param num 当前遍历位置
     * @param isClass 是否加入背景色
     */
    public void addCell(String value ,int num,boolean isClass) {
        try {
            Float.parseFloat(value);
            addCell("",num,isClass,Float.parseFloat(value));
        } catch (Exception e) {
            addCell(value,num,isClass,(float) 0);
        }
    }

    /** 加入单元格(文字)
     * @param value 字面的值
     * @param num 当前遍历位置
     * @param isClass 是否加入背景色
     */
    public void addCell(Float value ,int num,boolean isClass) {
        addCell("",num,isClass,value);
     }




    public void addCell(String value ,int num,boolean isClass,Float vvalue){
        XSSFCell cell = this.row.createCell(num+1);
        XSSFCellStyle borderStyle = this.workbook.createCellStyle();
        if(StringUtils.isNotBlank(value)) {
            cell.setCellValue(value);
        }else {
            cell.setCellValue(vvalue);
            cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
             XSSFDataFormat format = workbook.createDataFormat();
                borderStyle.setDataFormat(format.getFormat("#,##0.000"));
        }
        // 创建字体对象   
        Font ztFont = workbook.createFont();
        ztFont.setFontHeightInPoints((short)9);    // 将字体大小设置为9px   
        ztFont.setFontName("宋体");             // 将“新宋体”字体应用到当前单元格上   
        borderStyle.setFont(ztFont);                    // 将字体应用到样式上面   
        if(isClass) {
            //XSSFCell borderCell = this.row.createCell(num+1);  
            borderStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());// 设置背景色    
            borderStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            borderStyle.setBorderBottom(CellStyle.BORDER_THIN);   
            borderStyle.setBorderTop(CellStyle.BORDER_THIN);   
            borderStyle.setBorderLeft(CellStyle.BORDER_THIN);   
            borderStyle.setBorderRight(CellStyle.BORDER_THIN);  
        }
        cell.setCellStyle(borderStyle);


    }


    /**
     * 复制文件
     * 
     * @param s源文件
     * 
     * @param t复制到的新文件
     */
    public static void fileChannelCopy(File s, File t) {
        try {
            InputStream in = null;
            OutputStream out = null;
            try {
                in = new BufferedInputStream(new FileInputStream(s), 1024);
                out = new BufferedOutputStream(new FileOutputStream(t), 1024);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
            } finally {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 文本替换
     * @param map(键值对)
     * @param sheet
     */
    public void  replaceExcelDate () {

        int rowNum = sheet.getLastRowNum();
        for(int i = 0;i <= rowNum; i++){
            XSSFRow row = sheet.getRow(i);
            if(row == null) continue;
            for(int j = 0;j < row.getLastCellNum();j++){
                XSSFCell cell = row.getCell(j);
                if(cell == null) continue;
                if(cell.getCellType()== HSSFCell.CELL_TYPE_STRING) {
                    String key = cell.getStringCellValue();
                    if(StringUtils.isNoneBlank(key)){
                        if(map.containsKey(key)){
                            cell.setCellValue(map.get(key));
                        }
                    }
                }
            }
        }
    }

    /**
     * 输出数据流
     * @param os 输出数据流
     */
    public Exxx write(OutputStream os) throws IOException{
        workbook.write(os);
        os.flush();
        os.close();
        return this;
    }


    /**
     * 输出到客户端
     * @param fileName 输出文件名
     */
    public Exxx write(HttpServletResponse response, String fileName) throws IOException{
        response.reset();
        response.setContentType("application/octet-stream; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename="+Encodes.urlEncode(fileName));
        write(response.getOutputStream());
        return this;
    }


    /**
     * 输出到文件
     * @param fileName 输出文件名
     */
    public Exxx writeFile() throws FileNotFoundException, IOException{
        this.write(fos);
        fos.flush();
        fos.close();    
        return this;
    }

/*  测试方法
    public static void main(String[] args) {
        Exxx ee = new Exxx("H:\\存货总账模板.xlsx", 5);
        //替换模板的文本
        ee.map.put("ttime", "2016-06-07 12:00:00");
        ee.map.put("name", "测试");
        ee.replaceExcelDate();


        // 定义一个list集合假数据
        List<Map<String, Object>> lst = new ArrayList();
        Map<String, Object> map1 = new HashMap<String, Object>();
        for (int i = 0; i < 10; i++) {
            map1.put("id" + i, i);
            lst.add(map1);
        }
        for (int m = 0; m < lst.size(); m++) {
            Map<String, Object> map = lst.get(m);
            ee.addRow(m);
            for (int i = 0; i < 17; i++) {
                String value = map.get("id" + m) + "";
                if (value.equals("null")) {
                    value = "0";
                }
                ee.addCell(value, i, true);
            }
        }
        try {
            ee.writeFile();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/

}

图片传不上来,有点尴尬,作为技术博客备用,有问题大家请留言

猜你喜欢

转载自blog.csdn.net/s1040342522/article/details/78028377