欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用POI生成Excel文件的典型例子【基于poi3.0 附源码】 javapoiExcel 

程序员文章站 2022-07-15 08:16:05
...

用POI生成Excel文件的典型例子,基于poi3.0

ExportExcleDemo.java:

 

package com;
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.HSSFFont;
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 ExportExcleDemo {

	/**
	 * 
	 * 功能描述:用POI生成Excel文件的典型例子
	 * 基于poi3.0
	 * @author http://xp9802.iteye.com
	 * create on: 2011-11-29
	 *
	 */
	public static void main(String[] args) {
			HSSFWorkbook workbook = new HSSFWorkbook();

			int begin = 1;
			int end = 50;

			HSSFSheet sheet = workbook.createSheet();

			HSSFCellStyle cellStyleHead = workbook.createCellStyle();
			HSSFCellStyle cellStyleContent = workbook.createCellStyle();

			HSSFFont font1 = workbook.createFont();
			HSSFFont font2 = workbook.createFont();

			font1.setFontHeightInPoints((short) 12);
			font1.setColor((short)2);
			font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

			font2.setFontHeightInPoints((short) 10);
			font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);

			cellStyleHead.setFont(font1);
			cellStyleContent.setFont(font2);

			int rowIndex = 0;
			int colIndex = 0;
			HSSFRow row = sheet.createRow(rowIndex++);
			HSSFCell cell = row.createCell((short) colIndex++);
			String[] headTitles = { "第1列头部", "第2列头部", "第3列头部" };
			for (int i = 0; i < headTitles.length; i++) {
				cell = row.createCell((short) i);
				cell.setCellStyle(cellStyleHead);
				cell.setCellValue(new HSSFRichTextString(headTitles[i]));
			}

			for (int i = begin; i < end; i++) {
				row = sheet.createRow(rowIndex++);
				int index = 0;
				HSSFCell cell4 = row.createCell((short) index++);
				HSSFCell cell5 = row.createCell((short) index++);
				HSSFCell cell6 = row.createCell((short) index++);
				cell4.setCellStyle(cellStyleContent);
				cell5.setCellStyle(cellStyleContent);
				cell6.setCellStyle(cellStyleContent);
				cell4.setCellValue(new HSSFRichTextString("第1列数据"));
				cell5.setCellValue(new HSSFRichTextString("第2列数据"));
				cell6.setCellValue(new HSSFRichTextString("第3列数据"));
			}
			for (int i = 0; i < 3; i++) {
				sheet.autoSizeColumn((short) i);
			}
			File f=new File("D:\\exampleExcle.xls");
			FileOutputStream outputStream;
			try {
				outputStream = new FileOutputStream(f);
				try {
					workbook.write(outputStream);
				} catch (IOException e) {
					e.printStackTrace();
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}

	}

  

源码解压密码为:xp9802.iteye.com

相关标签: java poi Excel