java生成csv文件工具类

工具类:

import cn.hutool.core.io.FileTypeUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.common.primitives.Bytes;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.ClientAnchor;

import javax.activation.MimetypesFileTypeMap;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.Field;
import java.util.List;

public class CVSUtil {

    //data為數據列表
    //title為欄位名稱
    //注意:data列表內的對象屬性必須和標題順序一一對應
    public static void creatAndDownloadCVSFile(List data, String[] title, HttpServletResponse response) throws Exception {

        StringBuffer write = new StringBuffer();
        String enter = "\r\n";
        if(title!=null&&title.length!=0){                        //寫入標題列
            for(int i=0;i<title.length;i++){
                write.append(title[i]);
                if(i<title.length-1){
                    write.append(",");
                }else{
                    write.append(enter);
                }
            }
        }
        if(data!=null&&data.size()!=0){
            for(int i=0;i<data.size();i++){
                Object obj = data.get(i);
                Class<?> clazz = obj.getClass();
                Field[] fields = clazz.getDeclaredFields();
                PropertyUtilsBean p = new PropertyUtilsBean();
                for (int k=0;k<fields.length;k++){
                    String value = object2Str(p.getProperty(obj,fields[k].getName()));
                    if("taxGather".equals(fields[k].getName())){
                        write.append(value);
                        continue;
                    }
                    if(value.contains(",")){
                        value=value.replaceAll(",", ",");//去除,和\r\n以免對cvs讀寫造成影響
                    }
                    if(value.contains("\r\n")){
                        value=value.replaceAll("\r\n", "。");
                    }
                    if(value!=null&&!"".equals(value)){
                        write.append(value);
                    }else {
                        write.append(" ");
                    }
                    if(k<title.length-1){
                        write.append(",");
                    }
                }
                write.append(enter); //換行
            }
        }
        String write_tmp=new String(write);
        byte commonCsvHead[] = {(byte) 0xEF, (byte) 0xBB,(byte) 0xBF};//UTF-8 BOM頭避免中文亂碼
        InputStream is = new ByteArrayInputStream(Bytes.concat(commonCsvHead,write_tmp.getBytes()));
        // 設置response參數
        response.reset();
        response.setContentType("text/plain;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String((IdWorker.getIdStr() + ".csv").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }

    }
    public static String object2Str(Object param) {
        if(param==null){
            return "";
        }
        return "\t"+String.valueOf(param);
    }



    public static void creatAndDownloadCSVFile(List data, String[] title, HttpServletResponse response) throws Exception {

        StringBuffer write = new StringBuffer();
        String enter = "\r\n";
        if(title!=null&&title.length!=0){                        //寫入標題列
            for(int i=0;i<title.length;i++){
                write.append(title[i]);
                if(i<title.length-1){
                    write.append(",");
                }else{
                    write.append(enter);
                }
            }
        }
        if(data!=null&&data.size()!=0){
            for(int i=0;i<data.size();i++){
                Object obj = data.get(i);
                Class<?> clazz = obj.getClass();
                Field[] fields = clazz.getDeclaredFields();
                PropertyUtilsBean p = new PropertyUtilsBean();
                for (int k=0;k<fields.length;k++){
                    String value = object2Str(p.getProperty(obj,fields[k].getName()));
                    if(value.contains(",")){
                        value=value.replaceAll(",", ",");//去除,和\r\n以免對cvs讀寫造成影響
                    }
                    if(value.contains("\r\n")){
                        value=value.replaceAll("\r\n", "。");
                    }
                    if(value!=null&&!"".equals(value)){
                        write.append(value);
                    }else {
                        write.append(" ");
                    }
                    if(k<title.length-1){
                        write.append(",");
                    }
                }
                write.append(enter); //換行
            }
        }
        String write_tmp=new String(write);
        byte commonCsvHead[] = {(byte) 0xEF, (byte) 0xBB,(byte) 0xBF};//UTF-8 BOM頭避免中文亂碼
        InputStream is = new ByteArrayInputStream(Bytes.concat(commonCsvHead,write_tmp.getBytes()));
        // 設置response參數
        response.reset();
        response.setContentType("text/plain;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String((IdWorker.getIdStr() + ".csv").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }

    }


    public static void insertImageToExcel(File file, HSSFSheet sheet, HSSFWorkbook workbook, int[] pictureProperties){

        BufferedImage bufferImg = null;
        try {
            ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
            bufferImg = ImageIO.read(file);
            ImageIO.write(bufferImg, "jpg", byteArrayOut);

            //畫圖的頂級管理器,一個sheet隻能獲取一個(一定要注意這點)
            HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
            //anchor主要用於設置圖片的屬性
            HSSFClientAnchor anchor = new HSSFClientAnchor(
                    pictureProperties[0],
                    pictureProperties[1],
                    pictureProperties[2],
                    pictureProperties[3],
                    (short) pictureProperties[4],
                    pictureProperties[5],
                    (short)pictureProperties[6],
                    pictureProperties[7]);
            anchor.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);
            //插入圖片
            patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        FileOutputStream fileOut = null;
        BufferedImage bufferImg = null;
        //先把讀進來的圖片放到一個ByteArrayOutputStream中,以便產生ByteArray
        try {
            ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
            File file = new File("D:\\logo.png");
            bufferImg = ImageIO.read(file);
            ImageIO.write(bufferImg, "jpg", byteArrayOut);

            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet1 = wb.createSheet("test picture");
            int[] pictureProperties = {0,0,1023,255,5,6,5,6};
            insertImageToExcel(file,sheet1,wb,pictureProperties);
            fileOut = new FileOutputStream("D:/測試Excel"+String.valueOf(System.currentTimeMillis())+".xls");
            // 寫入excel文件
            wb.write(fileOut);
            System.out.println("----Excle文件已生成------");
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(fileOut != null){
                try {
                    fileOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}

业务方法中调用工具类代码:

// 查詢數據庫
List<OpenAcctActivityVO> activityVOList = activityAndAuthMapper.queryActivity(...);

// 定義表頭內容
String[] titles = {"日期時間", "用戶ID", "用戶角色", "XXXX", "XXXX"};
// 下載文件
CVSUtil.creatAndDownloadCVSFile(activityVOList, titles, httpServletResponse);

你可能感兴趣的:(小知识点,java)