poi实现将数据输出到Excel表格当中

今天简单的学习了一下POI,一下是所使用到的jar,这些jar可以到apache去下载

下面简单的说一下里面的一些类和一些作用:

package com.test.util;

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

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Font;

public class OutPutExcelTest {

    public static void outputExcel(){

        //创建一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建一个sheet
        HSSFSheet sheet = wb.createSheet("用户信息");
        sheet.setColumnWidth(0, 5000); //设置第一列的宽度
        sheet.setColumnWidth(1, 5000); //设置第二列的宽度
        sheet.setColumnWidth(2, 5000); //设置第三列的宽度
        
        
        //创建单元格样式对象
        HSSFCellStyle style = wb.createCellStyle();
        style.setVerticalAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setFillBackgroundColor((short)8);
        
        //创建字体对象
        Font font = wb.createFont();
        font.setBoldweight(Font.BOLDWEIGHT_BOLD);  //字体宽度
        font.setFontName("宋体");  //设置字体类型
        font.setItalic(false); //这只是否为斜体
        //设置字体样式
        style.setFont(font);
        
        
        //创建一行
        HSSFRow row0 = sheet.createRow(0);
        //设置行样式
        row0.setRowStyle(style);
        
        HSSFCell cell0_0 = row0.createCell(0);
        cell0_0.setCellStyle(style); //设置单元格样式
        cell0_0.setCellValue("姓名");
        HSSFCell cell0_1 = row0.createCell(1);
        cell0_1.setCellValue("性别");
        HSSFCell cell0_2 = row0.createCell(2);
        cell0_2.setCellValue("住址");
        
        for(int i = 1; i < 100; i ++){
            //创建行
            HSSFRow row = sheet.createRow(i);
            for(int j = 0; j < 10; j++){
                HSSFCell cell = row.createCell(j);
                cell.setCellValue("这是第"+(i+1)+"行,第"+(j+1)+"列");
            }
        }
        
        
        
        
        
        FileOutputStream fos  = null;
        try {
            fos = new FileOutputStream(new File("D:\未命名.xls"));
            wb.write(fos);
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
    }
    
    public static void main(String[] args) {

  //测试文件
        OutPutExcelTest.outputExcel();
    }
}
该代码能够直接的执行,复制粘贴可以直接运行,只是简单的做了一个输出,这个只要明白了,做数据的输出应该也不是问题。

原文地址:https://www.cnblogs.com/tangkai/p/poi.html