使用pio添加excel表格批註並保存

public static void main(String[] args) throws Exception {
    File file = new File("C:\\Users\\px\\Desktop\\xxxx.xls");
    addPostil(file,"Sheet2",5,0,"俺是批註");
}

/**
* 添加批註
* @param file 文件
* @param sheetName sheet名
* @param rownum 行號
* @param column 列號
* @param postilStr 批註名稱
* @throws Exception
*/
public static void addPostil(File file, String sheetName, int rownum,int column,String postilStr) throws Exception {
    FileInputStream exlFile = new FileInputStream(file);

    // POI給出的解決兼容Excel 2003和2007以上版本的方法
    Workbook workbook = WorkbookFactory.create(exlFile);

    if (workbook instanceof HSSFWorkbook) {
        postilHSSF(((HSSFWorkbook) workbook).getSheet(sheetName),rownum,column,postilStr);
    } else if (workbook instanceof XSSFWorkbook) {
        postilXSSF(((XSSFWorkbook) workbook).getSheet(sheetName),rownum,column,postilStr);
    }
    exlFile.close();// 關閉文件輸入流
    FileOutputStream fos = new FileOutputStream(file);
    workbook.write(fos);
    fos.close();// 關閉文件輸出流
}

public static void postilHSSF(HSSFSheet sheet,int rownum,int column,String postilStr){
    //創建繪圖對象
    HSSFPatriarch p=sheet.createDrawingPatriarch();
    //創建單元格對象
    HSSFCell cell=sheet.createRow(rownum).createCell(column);
    //獲取批註對象
    //(int dx1, int dy1, int dx2, int dy2, short col1, int row1, short col2, int row2)
    //前四個參數是座標點,後四個參數是編輯和顯示批註時的大小.
    HSSFComment comment=p.createComment(new HSSFClientAnchor(0,0,0,0,(short)3,3,(short)5,6));
    //輸入批註信息
    comment.setString(new HSSFRichTextString(postilStr));
    //將批註添加到單元格對象中
    cell.setCellComment(comment);
}

public static void postilXSSF(XSSFSheet sheet,int rownum,int column,String postilStr){
    //創建繪圖對象
    XSSFDrawing p = sheet.createDrawingPatriarch();
    //創建單元格對象
    XSSFCell cell = sheet.createRow(rownum).createCell(column);
    //獲取批註對象
    //(int dx1, int dy1, int dx2, int dy2, short col1, int row1, short col2, int row2)
    //前四個參數是座標點,後四個參數是編輯和顯示批註時的大小.
    XSSFComment comment = p.createCellComment(new XSSFClientAnchor(0,0,0,0,(short)3,3,(short)5,6));
    //輸入批註信息
    comment.setString(new XSSFRichTextString(postilStr));
    //將批註添加到單元格對象中
    cell.setCellComment(comment);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章