apache POI学习(三)——生成带格式的excel表格

apache POI学习(三)——生成带格式的excel表格

根据官方提供的代码,写一个带有简单格式的excel。
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

import javax.lang.model.element.VariableElement;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

public class Main {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// create a new file
		FileOutputStream out = null;
		try {
			out = new FileOutputStream("d:/123/workbook.xls");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// create a new workbook
		Workbook wb = new HSSFWorkbook();
		// create a new sheet
		Sheet s = wb.createSheet();
		// set the SheetName
		wb.setSheetName(0, "sheet name00");
		
		//item CellStyle
		CellStyle cs = wb.createCellStyle();
		Font f = wb.createFont();
		f.setFontHeightInPoints((short)Font.COLOR_RED);
		f.setColor((short)0xc);
		cs.setFont(f);
		
		//title CellStyle
		CellStyle csTitle = wb.createCellStyle();
		Font fTitle = wb.createFont();
		fTitle.setFontHeightInPoints((short)30);
		fTitle.setColor((short)Font.COLOR_RED);
		fTitle.setBoldweight(Font.BOLDWEIGHT_BOLD);
		csTitle.setFont(fTitle);
		
		// declare a row object reference
		Row r = null;
		// declare a cell object reference
		Cell c = null;
		
		s.setDefaultColumnWidth(25);
		r = s.createRow(0);
		r.setHeightInPoints((short)40);
		c = r.createCell(1);
		c.setCellValue("this is a test title!");
		c.setCellStyle(csTitle);
		
		r=s.createRow(1);
		c= r.createCell(2);
		c.setCellValue("打印时间:2016-8-31 17:47:18");
		for (int rownum = 2; rownum < 6; rownum++) {
			r = s.createRow(rownum);
			for (int cellnum = 0; cellnum < 4; cellnum++) {
				c = r.createCell(cellnum);
				c.setCellValue("rownum=" + rownum + " colnum=" + cellnum);
				c.setCellStyle(cs);
			}
		}
		
		// demonstrate adding/naming and deleting a sheet
		// create a sheet, set its title then delete it
		/*s = wb.createSheet();
		wb.setSheetName(1, "DeletedSheet");
		wb.removeSheetAt(1);*/
		//end deleted sheet

		// write the workbook to the output stream
		// close our file (don't blow out our file handles
		try {
			wb.write(out);
			out.close();
			wb.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

生成的excel截图:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值