代码改变世界

POI 生成exel报表

2017-04-11 19:31  甘雨路  阅读(1027)  评论(0编辑  收藏  举报

去官网下载相关jar包   http://poi.apache.org/

package poi.zr.com;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class TestUtil {
    
    public static void main(String[] args) {
        
        OutputStream outputStream = null;
        
        try {
            outputStream = new FileOutputStream(new File("C:/Users/111/Desktop/测试.xls"));
           write(outputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    public static void write(OutputStream outputStream) throws IOException{
        // 初始化一个HSSFWorkbook对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建一个表
        HSSFSheet sheet = workbook.createSheet("李矾");
        // 创建行
        HSSFRow row = sheet.createRow(0);
        // 创建单元格
        HSSFCell cell0 = row.createCell(0);
        cell0.setCellValue(new HSSFRichTextString("姓名"));
        
        HSSFCell cell1 = row.createCell(1);
        cell1.setCellValue(new HSSFRichTextString("年龄"));
        
        HSSFCell cell2 = row.createCell(2);
        cell2.setCellValue(new HSSFRichTextString("基本信息"));
        
        // 遍历
        for (int i = 0; i < 10; i++) {
            // 创建行
            HSSFRow rowi = sheet.createRow(i+1);
            // 创建单元格
            for (int j = 0; j < 3; j++) {
                HSSFCell celli = rowi.createCell(j);
                celli.setCellValue(new HSSFRichTextString("第"+(i+1)+"行"+",第"+(j)+"列"));
            }
            
        }
        
        workbook.write(outputStream);
    }
}