JAVA利用POI操作excel


1.创建一个新的Excle工作薄



// 创建新的Excel 工作簿

HSSFWorkbook workbook = new HSSFWorkbook();



// 在Excel工作簿中建一工作表,其名为缺省值, 也可以指定Sheet名称

HSSFSheet sheet = workbook.createSheet();

//HSSFSheet sheet = workbook.createSheet("SheetName"); 



2. 创建新行(row),并将单元格(cell)放入其中. 行号从0开始计算.



HSSFRow row = sheet.createRow((short) 1);

3.设置sheet名称和单元格内容为中文



wb.setSheetName(n, "中文",HSSFCell.ENCODING_UTF_16);       

cell.setEncoding((short) 1);   

cell.setCellValue("中文");  

4.设置列宽、行高



sheet.setColumnWidth((short)column,(short)width);   

row.setHeight((short)height);  

5.添加区域,合并单元格



Region region = new Region((short)rowFrom,(short)columnFrom,(short)rowTo,(short)columnTo);   

sheet.addMergedRegion(region);   

//得到所有区域   

sheet.getNumMergedRegions()  

6.设置单元格边框格式

虚线HSSFCellStyle.BORDER_DOTTED

实线HSSFCellStyle.BORDER_THIN



public static HSSFCellStyle getCellStyle(short type){      

     HSSFWorkbook wb = new HSSFWorkbook();   

     HSSFCellStyle style = wb.createCellStyle();    

     style.setBorderBottom(type);//下边框    

      style.setBorderLeft(type);//左边框    

      style.setBorderRight(type);//右边框    

      style.setBorderTop(type);//上边框    

      return style;   

}  

7.设置字体和内容位置



HSSFFont f  = wb.createFont();   

f.setFontHeightInPoints((short) 11);//字号   

f.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);//加粗   

style.setFont(f);   

style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//左右居中   

style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//上下居中   

style.setRotation(short rotation);//单元格内容的旋转的角度   

HSSFDataFormat df = wb.createDataFormat();   

style1.setDataFormat(df.getFormat("0.00%"));//设置单元格数据格式   

cell.setCellFormula(string);//给单元格设公式   

style.setRotation(short rotation);//单元格内容的旋转的角度   

cell.setCellStyle(style);  

8.插入图片



//先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray   

      ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();   

      BufferedImage bufferImg = ImageIO.read(new File("ok.jpg"));   

      ImageIO.write(bufferImg,"jpg",byteArrayOut);   

//读进一个excel模版   

FileInputStream fos = new FileInputStream(filePathName+"/stencil.xlt");    

fs = new POIFSFileSystem(fos);   

//创建一个工作薄   

HSSFWorkbook wb = new HSSFWorkbook(fs);   

HSSFSheet sheet = wb.getSheetAt(0);   

HSSFPatriarch patriarch = sheet.createDrawingPatriarch();   

HSSFClientAnchor anchor = new HSSFClientAnchor(0,0,1023,255,(short) 0,0,(short)10,10);        

patriarch.createPicture(anchor , wb.addPicture(byteArrayOut.toByteArray(),HSSFWorkbook.PICTURE_TYPE_JPEG));

你可能感兴趣的:(Excel)