package cn.itcast.cc.excel.exports; import java.io.FileOutputStream; import java.util.Date; import org.apache.poi.hssf.usermodel.HSSFCell; 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.IndexedColors; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.junit.Test; /** * 测试类,每个方法都是独立的。 * @author Administrator * */ public class ExportExcel { /** * 测试WorkBook * @throws Exception */ @Test public void testCreateExcel() throws Exception{ // 创建Workbook Workbook wb = new HSSFWorkbook(); FileOutputStream fileOut = new FileOutputStream("C:/workbook.xls"); // 写出到文件 wb.write(fileOut); fileOut.close(); } /** * 测试Sheet * @throws Exception */ @Test public void testCreateSheet() throws Exception{ Workbook wb = new HSSFWorkbook(); FileOutputStream fileOut = new FileOutputStream("C:/workbook.xls"); // 创建sheet Sheet sheet = wb.createSheet("HelloWorld!"); // 设置第1列宽度,列号以0开始。 sheet.setColumnWidth(0,10000); wb.write(fileOut); fileOut.close(); } /** * 测试Cell * @throws Exception */ @Test public void testCreateCell() throws Exception{ Workbook wb = new HSSFWorkbook(); FileOutputStream fileOut = new FileOutputStream("C:/workbook.xls"); // 创建sheet Sheet sheet = wb.createSheet("HelloWorld!"); // 设置第1列宽度 sheet.setColumnWidth(0,10000); // 创建一行,行号以0开始。 Row row = sheet.createRow(0); // 单元格的样式属性 CellStyle style = wb.createCellStyle(); // 底边表格线 style.setBorderBottom(CellStyle.BORDER_DOUBLE); style.setBottomBorderColor(IndexedColors.RED.getIndex()); style.setDataFormat(wb.getCreationHelper().createDataFormat().getFormat("m/d/yy h:mm")); // 创建一个单元格,参数为列号。 Cell cell = row.createCell(0); cell.setCellStyle(style); // 向单元格中添加各种类型数据 cell.setCellValue(new Date()); row.createCell(1).setCellValue(1.1); row.createCell(2).setCellValue("文本型"); row.createCell(3).setCellValue(true); row.createCell(4).setCellType(HSSFCell.CELL_TYPE_ERROR); wb.write(fileOut); fileOut.close(); } } |