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; /** * 測(cè)試類,每個(gè)方法都是獨(dú)立的。 * @author Administrator * */ public class ExportExcel { /** * 測(cè)試WorkBook * @throws Exception */ @Test public void testCreateExcel() throws Exception{ // 創(chuàng)建Workbook Workbook wb = new HSSFWorkbook(); FileOutputStream fileOut = new FileOutputStream("C:/workbook.xls"); // 寫出到文件 wb.write(fileOut); fileOut.close(); } /** * 測(cè)試Sheet * @throws Exception */ @Test public void testCreateSheet() throws Exception{ Workbook wb = new HSSFWorkbook(); FileOutputStream fileOut = new FileOutputStream("C:/workbook.xls"); // 創(chuàng)建sheet Sheet sheet = wb.createSheet("HelloWorld!"); // 設(shè)置第1列寬度,列號(hào)以0開(kāi)始。 sheet.setColumnWidth(0,10000); wb.write(fileOut); fileOut.close(); } /** * 測(cè)試Cell * @throws Exception */ @Test public void testCreateCell() throws Exception{ Workbook wb = new HSSFWorkbook(); FileOutputStream fileOut = new FileOutputStream("C:/workbook.xls"); // 創(chuàng)建sheet Sheet sheet = wb.createSheet("HelloWorld!"); // 設(shè)置第1列寬度 sheet.setColumnWidth(0,10000); // 創(chuàng)建一行,行號(hào)以0開(kāi)始。 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")); // 創(chuàng)建一個(gè)單元格,參數(shù)為列號(hào)。 Cell cell = row.createCell(0); cell.setCellStyle(style); // 向單元格中添加各種類型數(shù)據(jù) 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(); } } |