您的位置:首页 > 运维架构 > Apache

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

2016-08-31 18:01 447 查看

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截图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐