import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFComment;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
public class PoiCreateExcelTest...{
public static void main(String[]args)...{
//建立新的Excel工做簿
HSSFWorkbookworkbook=new HSSFWorkbook();
//在Excel工做簿中建一工做表,其名爲缺省值,也能夠指定Sheet名稱
HSSFSheetsheet=workbook.createSheet();
//HSSFSheetsheet=workbook.createSheet("SheetName");
//用於格式化單元格的數據
HSSFDataFormatformat=workbook.createDataFormat();
//建立新行(row),並將單元格(cell)放入其中.行號從0開始計算.
HSSFRowrow=sheet.createRow((short)1);
//設置字體
HSSFFontfont=workbook.createFont();
font.setFontHeightInPoints((short)20);//字體高度
font.setColor(HSSFFont.COLOR_RED);//字體顏色
font.setFontName("黑體");//字體
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//寬度
font.setItalic(true);//是否使用斜體
//font.setStrikeout(true);//是否使用劃線
//設置單元格類型
HSSFCellStylecellStyle=workbook.createCellStyle();
cellStyle.setFont(font);
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平佈局:居中
cellStyle.setWrapText(true);
//添加單元格註釋
//建立HSSFPatriarch對象,HSSFPatriarch是全部註釋的容器.
HSSFPatriarchpatr=sheet.createDrawingPatriarch();
//定義註釋的大小和位置,詳見文檔
HSSFCommentcomment=patr.createComment(new HSSFClientAnchor(0,0,0,0,(short)4,2,(short)6,5));
//設置註釋內容
comment.setString(new HSSFRichTextString("能夠在POI中添加註釋!"));
//設置註釋做者.當鼠標移動到單元格上是能夠在狀態欄中看到該內容.
comment.setAuthor("Xuys.");
//建立單元格
HSSFCellcell=row.createCell((short)1);
HSSFRichTextStringhssfString=new HSSFRichTextString("HelloWorld!");
cell.setCellValue(hssfString);//設置單元格內容
cell.setCellStyle(cellStyle);//設置單元格樣式
cell.setCellType(HSSFCell.CELL_TYPE_STRING);//指定單元格格式:數值、公式或字符串
cell.setCellComment(comment);//添加註釋
//格式化數據
row=sheet.createRow((short)2);
cell=row.createCell((short)2);
cell.setCellValue(11111.25);
cellStyle=workbook.createCellStyle();
cellStyle.setDataFormat(format.getFormat("0.0"));
cell.setCellStyle(cellStyle);
row=sheet.createRow((short)3);
cell=row.createCell((short)3);
cell.setCellValue(9736279.073);
cellStyle=workbook.createCellStyle();
cellStyle.setDataFormat(format.getFormat("#,##0.0000"));
cell.setCellStyle(cellStyle);
sheet.autoSizeColumn((short)0);//調整第一列寬度
sheet.autoSizeColumn((short)1);//調整第二列寬度
sheet.autoSizeColumn((short)2);//調整第三列寬度
sheet.autoSizeColumn((short)3);//調整第四列寬度
try ...{
FileOutputStreamfileOut=new FileOutputStream("C:\3.xls");
workbook.write(fileOut);
fileOut.close();
}catch (Exceptione)...{
System.out.println(e.toString());
}
}
}