1. 程式人生 > >Java寫資料到txt、csv、xls檔案中

Java寫資料到txt、csv、xls檔案中

java實現寫大量資料到檔案中

  • 生成.txt檔案
  • 生成.csv檔案
  • 生成.xls檔案
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class CreateFileUtil {

    /**
     * 生成.TXT格式檔案,行數幾乎無上限
     */
public static boolean createTxtFile(List<Object[]> rows, String filePath, String fileName) { // 標記檔案生成是否成功 boolean flag = true; try { // 含檔名的全路徑 String fullPath = filePath + File.separator + fileName + ".txt"; File file = new File(fullPath); if (file.exists()) { // 如果已存在,刪除舊檔案 file.delete(); } file = new File(fullPath); file.createNewFile(); // 格式化浮點資料 NumberFormat formatter = NumberFormat.getNumberInstance(); formatter.setMaximumFractionDigits(10); // 設定最大小數位為10 // 格式化日期資料 SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); // 遍歷輸出每行 PrintWriter pfp = new PrintWriter(file, "UTF-8"); //設定輸出檔案的編碼為utf-8 for (Object[] rowData : rows) { StringBuffer thisLine = new StringBuffer(""); for (int i = 0; i < rowData.length; i++) { Object obj = rowData[i]; // 當前欄位 // 格式化資料 String field = ""; if (null != obj) { if (obj.getClass() == String.class) {   // 如果是字串 field = (String) obj; } else if (obj.getClass() == Double.class || obj.getClass() == Float.class) {   // 如果是浮點型 field = formatter.format(obj); // 格式化浮點數,使浮點數不以科學計數法輸出 } else if (obj.getClass() == Integer.class || obj.getClass() == Long.class || obj.getClass() == Short.class || obj.getClass() == Byte.class) {   // 如果是整形 field += obj; } else if (obj.getClass() == Date.class) {   // 如果是日期型別 field = sdf.format(obj); } } else { field = " "; // null時給一個空格佔位 } // 拼接所有欄位為一行資料,用tab鍵分隔 if (i < rowData.length - 1) {   // 不是最後一個元素 thisLine.append(field).append("\t"); } else {   // 是最後一個元素 thisLine.append(field); } } pfp.print(thisLine.toString() + "\n"); } pfp.close(); } catch (Exception e) { flag = false; e.printStackTrace(); } return flag; }

 

    /**
     * 生成.csv格式檔案,行數幾乎無上限
     */
    public static boolean createCsvFile(List<Object[]> rows, String filePath, String fileName) {
        // 標記檔案生成是否成功
        boolean flag = true;

        // 檔案輸出流
        BufferedWriter fileOutputStream = null;

        try {
            // 含檔名的全路徑
            String fullPath = filePath + File.separator + fileName + ".csv";

            File file = new File(fullPath);
            if (!file.getParentFile().exists()) { // 如果父目錄不存在,建立父目錄
                file.getParentFile().mkdirs();
            }
            if (file.exists()) { // 如果已存在,刪除舊檔案
                file.delete();
            }
            file = new File(fullPath);
            file.createNewFile();

            // 格式化浮點資料
            NumberFormat formatter = NumberFormat.getNumberInstance();
            formatter.setMaximumFractionDigits(10); // 設定最大小數位為10

            // 格式化日期資料
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

            // 例項化檔案輸出流
            fileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "GB2312"), 1024);

            // 遍歷輸出每行
            Iterator<Object[]> ite = rows.iterator();
            while (ite.hasNext()) {
                Object[] rowData = (Object[]) ite.next();
                for (int i = 0; i < rowData.length; i++) {
                    Object obj = rowData[i]; // 當前欄位
                    // 格式化資料
                    String field = "";
                    if (null != obj) {
                        if (obj.getClass() == String.class) { // 如果是字串
                            field = (String) obj;
                        } else if (obj.getClass() == Double.class || obj.getClass() == Float.class) { 
                            // 如果是浮點型
                            field = formatter.format(obj); // 格式化浮點數,使浮點數不以科學計數法輸出
                        } else if (obj.getClass() == Integer.class || obj.getClass() == Long.class
                                || obj.getClass() == Short.class || obj.getClass() == Byte.class) { 
                           // 如果是整形
                            field += obj;
                        } else if (obj.getClass() == Date.class) { // 如果是日期型別
                            field = sdf.format(obj);
                        }
                    } else {
                        field = " "; // null時給一個空格佔位
                    }
                    // 拼接所有欄位為一行資料
                    if (i < rowData.length - 1) { // 不是最後一個元素
                        fileOutputStream.write("\"" + field + "\"" + ",");
                    } else { // 是最後一個元素
                        fileOutputStream.write("\"" + field + "\"");
                    }
                }
                // 建立一個新行
                if (ite.hasNext()) {
                    fileOutputStream.newLine();
                }
            }
            fileOutputStream.flush();
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

 

   /**
     * 生成.xls格式檔案,單頁上限: 03版是65536行 ,07版的是1048576行, 10版不知
     */
    public static boolean createXlsFile(List<Object[]> rows, String filePath, String fileName) {
        // 標記檔案生成是否成功
        boolean flag = true;

        try {
            // 建立一個webbook,對應一個Excel檔案
            XSSFWorkbook wb = new XSSFWorkbook();

            // 在webbook中新增一個sheet,對應Excel檔案中的sheet
            XSSFSheet sheet = wb.createSheet(fileName);

            // 遍歷輸出每行
            for (int i = 0; i < rows.size(); i++) {
                Object[] rowData = rows.get(i); // 每一行的資料
                XSSFRow row = sheet.createRow(i);
                for (int j = 0; j < rowData.length; j++) {
                    XSSFCell cell = row.createCell(j);
                    // 假設只有三種類型的資料
                    if (rowData[j].getClass() == String.class) { // String型別數值
                        cell.setCellValue((String) rowData[j]);
                    } else if (rowData[j].getClass() == double.class) { // double型別數值
                        cell.setCellValue((Double) rowData[j]);
                    } else if (rowData[j].getClass() == int.class) { // int型別數值
                        cell.setCellValue((Integer) rowData[j]);
                    }
                }
            }

            String fullPath = filePath + File.separator + fileName + ".xls";// 含檔名的全路徑
            File file = new File(fullPath);
            if (!file.getParentFile().exists()) { // 如果父目錄不存在,建立父目錄
                file.getParentFile().mkdirs();
            }
            if (file.exists()) { // 如果已存在,刪除舊檔案
                file.delete();
            }
            file = new File(fullPath);
            file.createNewFile();
            FileOutputStream fileOut = new FileOutputStream(file); // 寫出資料到檔案
            wb.write(fileOut);
            fileOut.close();
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }
}