在EXCEL指定SHEET頁,指定文字位置,插入批註

Java操做EXCEL文件,利用POI,在EXCEL指定SHEET頁中指定文字位置處插入批註java

第一種:會覆蓋原來的備註apache

package excel;app

import java.io.FileInputStream;
import java.io.FileOutputStream;工具

import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFComment;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellReference;字體

public class ExcelUtils {
    public static void main(String[] args) {
        String fin = "E:\\ceshi\\hello.xls";
        String fout = "E:\\ceshi\\ceshi.xls";
        String sheetname = "火龍果";
        String cellmsg = "AAA";
        WriteLetter(fin, fout, sheetname, cellmsg);
    }
    /**
     * 
     * @param fin原始文件位置
     * @param fout 輸出文件位置
     * @param sheetname SHEET頁名稱
     * @param cellmsg    要查詢的文字位置
     */
    public static void WriteLetter(String fin, String fout, String sheetname, String cellmsg) {
        try (FileInputStream in = new FileInputStream(fin); FileOutputStream out = new FileOutputStream(fout);) {
            HSSFWorkbook workbook = new HSSFWorkbook(in);// 拿到文件轉化爲javapoi可操縱類型
            HSSFSheet sheet = null;
            Cell cellnew = null;
            Integer rownum = null;
            Integer colnum = null;
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {// 獲取每一個Sheet表
                sheet = workbook.getSheetAt(i);
                if (sheetname.equals(sheet.getSheetName())) {
                    Boolean flag = false;
                    for (Row row : sheet) {
                        if (flag) {
                            break;// 結束行循環
                        }
                        for (Cell cell : row) {
                            // 單元格的參照 ,根據行和列肯定某一個單元格的位置
                            CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
                            String cellname = "";
                            // 獲得單元格類型
                            switch (cell.getCellType()) {
                            case Cell.CELL_TYPE_STRING:// String類型單元格
                                // 輸出文本
                                cellname = cell.getRichStringCellValue().getString();
                                break;
                            case Cell.CELL_TYPE_NUMERIC:// 數字類型
                                // 檢查單元格是否包含一個Date類型
                                // 僅僅只檢查Excel內部的日期格式,
                                if (DateUtil.isCellDateFormatted(cell)) {
                                    // 輸出日期
                                    cellname = cell.getDateCellValue().toString();
                                } else {
                                    // 輸出數字
                                    cellname = cell.getNumericCellValue() + "";
                                }
                                break;
                            case Cell.CELL_TYPE_BOOLEAN:// Boolean類型
                                cellname = cell.getBooleanCellValue() + "";
                                break;
                            case Cell.CELL_TYPE_FORMULA:// 公式
                                // 輸出公式
                                cellname = cell.getCellFormula().toString();
                                break;
                            default:
                            }
                            if (cellmsg.equals(cellname)) {
                                System.out.println("找到指定位置了");
                                // 打印單元格的位置
                                System.out.print(cellRef.formatAsString());
                                rownum = 4;// TODO 計算要加批註的位置,行號和列號
                                colnum = 4;
                                flag = true;
                                break;
                            }
                        }
                    }
                    break;// 結束sheet循環
                }
            }
            // 建立繪圖對象
            HSSFPatriarch p = sheet.createDrawingPatriarch();
            // 建立單元格對象,批註插入到4行,1列,B5單元格
            // HSSFCell cell=sheet.createRow(4).createCell(1);
            // 獲取指定單元格
            // cell=sheet.getRow(cell.getRowIndex()).getCell(6);
            if (rownum == null || colnum == null) {
                throw new RuntimeException("查詢不到定位文字位置");
            }
            if (sheet.getRow(rownum) == null) {
                cellnew = sheet.createRow(rownum).createCell(colnum);
            } else {
                if (sheet.getRow(rownum).getCell(colnum) == null) {
                    cellnew = sheet.getRow(rownum).createCell(colnum);
                } else {
                    cellnew = sheet.getRow(rownum).getCell(colnum);
                }
            }
            // 插入單元格內容
            // cell.setCellValue(new HSSFRichTextString("批註"));
            // 獲取批註對象
            // (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("插件批註成功!插件批註成功!"));
            // 添加做者,選中B5單元格,看狀態欄
            comment.setAuthor("系統自動添加");
            // 將批註添加到單元格對象中
            cellnew.setCellComment(comment);
            workbook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}.net

 

第二種:xlsx格式的文件,不會覆蓋原來的備註,xls格式文件會覆蓋原來的備註插件

package excel;
import java.io.FileInputStream;
import java.io.FileOutputStream;excel

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class CellCommentCeshi {
     public static void main(String[] args) throws Exception {  
         FileInputStream in = new FileInputStream("E://ceshi//hello.xls");
            //1.建立一個工做簿對象  
            Workbook wb = WorkbookFactory.create(in);
            //2.獲得一個POI的工具類  
            CreationHelper factory = wb.getCreationHelper();  
            //3. 建立一個工做表  
            Sheet sheet =  wb.getSheetAt(0);
              
            //4.獲得一個換圖的對象  
            Drawing drawing = sheet.createDrawingPatriarch();  
            //5. ClientAnchor是附屬在WorkSheet上的一個對象,  其固定在一個單元格的左上角和右下角.  
            ClientAnchor anchor = factory.createClientAnchor();  
              
            //6. 建立一個單元格(2A單元格)  
            Cell cell0 = sheet.createRow(1).createCell(0);  
            //6.1. 對這個單元格設置值  
            cell0.setCellValue("Test");  
            //6.2. 對這個單元格加上註解  
            Comment comment0 = drawing.createCellComment(anchor);  
            RichTextString str0 = factory.createRichTextString("Hello, World!");  
            comment0.setString(str0);  
            comment0.setAuthor("Apache POI");  
            cell0.setCellComment(comment0);  
              
            //7. 建立一個單元格(4F單元格)  
            Cell cell1 = sheet.createRow(3).createCell(5);  
            //7.1. 對這個單元格設置值  
            cell1.setCellValue("F4");  
            //7.2. 對這個單元格加上註解  
            Comment comment1 = drawing.createCellComment(anchor);  
            RichTextString str1 = factory.createRichTextString("Hello, World!");  
            comment1.setString(str1);  
            comment1.setAuthor("Apache POI");  
            cell1.setCellComment(comment1);  
      
            //8. 建立一個單元格(4F單元格)  
            Cell cell2 = sheet.createRow(2).createCell(2);  
            cell2.setCellValue("C3");  
      
            Comment comment2 = drawing.createCellComment(anchor);  
            RichTextString str2 = factory.createRichTextString("XSSF can set cell comments");  
            //9。爲註解設置字體  
            Font font = wb.createFont();  
            font.setFontName("Arial");  
            font.setFontHeightInPoints((short)14);  
            font.setBoldweight(Font.BOLDWEIGHT_BOLD);  
            font.setColor(IndexedColors.RED.getIndex());  
            str2.applyFont(font);  
      
            comment2.setString(str2);  
            comment2.setAuthor("Apache POI");  
            comment2.setColumn(2);  
            comment2.setRow(2);  
            //10. 保存成Excel文件  
            String fname = "E://ceshi//hello2.xls";  
            FileOutputStream out = new FileOutputStream(fname);  
            wb.write(out);  
            out.close();  
      
        }  
}
 orm

相關文章
相關標籤/搜索