`

POI 生成excel文件

阅读更多
package com.zhao.poi.test;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.ss.util.CellRangeAddress;


public class TestPoi {

	public static void main(String[] args)  {
		
		Workbook  wb = new HSSFWorkbook();
		Sheet sheet1 = wb.createSheet("new sheet");
		Sheet sheet2 = wb.createSheet("second sheet");
		
		// Create a row and put some cells in it. Rows are 0 based.
	    Row row = sheet2.createRow((short)0);
	    // Create a cell and put a value in it.
	    Cell cell = row.createCell(0);
	    cell.setCellValue(1);

	    // Or do it on one line.
	    row.createCell(1).setCellValue(1.2);
	    row.createCell(2).setCellValue(12);
	    row.createCell(3).setCellValue(22);

	    row.createCell(4).setCellFormula("SUM(A1:D1)");
	    
	    Row row2 = sheet2.createRow((short)1);
	    row2.createCell(0).setCellValue(11);
	    row2.createCell(1).setCellValue(22);
	    //row2.createCell(2).setCellValue(22);
	    Row row3 = sheet2.createRow((short)2);
	    row3.createCell(0).setCellValue(23);
	    Row row4 = sheet2.createRow((short)3);
	    row4.createCell(0).setCellValue(33);
	    
	    Row row5 = sheet2.createRow((short)4);
	    row5.createCell(0).setCellFormula("SUM(A1:A4)");

	    sheet2.addMergedRegion(new CellRangeAddress(1,(short)1,1,(short)2));//指定合并区域 

		FileOutputStream fileOut;
		try {
			//设当前活动工作表
			wb.setActiveSheet(1);
			//设当前标签
			wb.setSelectedTab(1);
			
			fileOut = new FileOutputStream("workbook.xls");
			wb.write(fileOut);
		    fileOut.close();
		    System.out.println("ok");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    

		

	}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics