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(); } } |