POI 导出Demo TestExcelPOI.java

来源:互联网 发布:2017淘宝生意差 编辑:程序博客网 时间:2024/05/21 14:08

package com.text;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.poi.ss.usermodel.Cell;
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.streaming.SXSSFWorkbook;

public class TestExcelPOI {
 public static void main(String[] args) {
  String newFileName = "d:\\test_performance.xls";
  int rows = 10;
  int cols = 5;
  Date time = new Date();
  Workbook book = null;
  Sheet sheet = null;
  BufferedOutputStream out = null;
  try {
   
   // 缓存128在内存
   book = new SXSSFWorkbook(128);
   sheet = book.createSheet("OQC抽检");
   exportToExcel(book, sheet, rows, cols);
   out = new BufferedOutputStream(new FileOutputStream(newFileName));
   book.write(out);
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (out != null) {
    try {
     out.close();
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  }
  System.out.println(new Date().getTime() - time.getTime());
 }

 public static void exportToExcel(Workbook book, Sheet sheet, int row,
  int col) throws Exception {
  for (int i = 0; i < row; i++) {
   Row sheetRow = sheet.createRow(i);
   for (int j = 0; j < col; j++) {
    Cell cell = sheetRow.createCell(j);
    String value = i + "_" + j;
    if (j == 2) {
     SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
     value = sdf1.format(new Date());
    }
    cell.setCellValue(value);
   }
  }
 }
}

原创粉丝点击