1. 程式人生 > >poi 操作excel

poi 操作excel

1、removeRow(Row row):刪除行,但不會實現下面行上移

2、shiftRows(int startRow, int endRow, n):start行到end行移動n行,n正上移,n負下移。合併過單元格的移動會報錯

3、removeMergedRegion(int deleRow):刪除樣式

4、表、行、單元格迴圈的時候都是從0開始讀

5、shiftRows無法向上移動,個人猜測,removeRow刪除行只有在write方法呼叫後才生效,所以上移會出現合併的單元格無法移動。

public void func(Workbook wb) {
	for (int i = 0; i < wb.getNumberOfSheets(); i++) {
		Sheet sheet = wb.getSheetAt(i);
		for (int rr = 0; rr < sheet.getPhysicalNumberOfRows(); rr++) { // 遍歷有記錄的所有行,空行不記錄
			Row row = sheet.getRow(rr);
			if (row == null) {
				continue;
			}
			for (int cc = 0; cc < row.getPhysicalNumberOfCells(); cc++) { // 遍歷所有列,空列不記錄
				Cell cell = row.getCell(cc);
				CellType cellType = cell.getCellTypeEnum();
				String value;
				switch (cellType) {
				case STRING:
					value = cell.getStringCellValue();
				case NUMERIC:
					value = String.valueOf(cell.getNumericCellValue());
				case BOOLEAN:
					value = String.valueOf(cell.getBooleanCellValue());
				default:
					value = "";
				}
				cell.setCellValue(value);
			}
		}
	}
}

二、關於POI3.17的一些問題

1、使用poi3.17版本生成excel的一些樣式設定http://blog.sina.com.cn/s/blog_c2aff7060102xlj4.html

2、不推薦getCellType(),推薦getCellTypeEnum()

3、POI使用詳解https://www.cnblogs.com/huajiezh/p/5467821.html

4、Workbook wb = new HSSFWorkbook();  //.xls  excel95, 97, 2000,2003等版本

                            = new XSSFWorkbook(); //.xlsx  excel2007及以後版本

5、Sheet sheet = wb.createSheet("name");//sheet

6、Row row = sheet.createRow(0);            //建立row   某行第0行

row.setHeightInPoints(50);                //設定行高

7、Cell cell = row.createCell(0);        //建立cell

如果要多列併合並單元格 並且給多列設定相同的樣式,則要建立多個cell,每個cell都要呼叫setCellStyle(style)

CellRangeAddress region = new CellRangeAddress(0, 1, 0, 3);        //合併列     0-1行  0-3列 合併單元格
sheet.addMergedRegion(region);                                //設定合併格式

8、cellStyle

CellStyle style = wb.createCellStyle();//單元格格式
        style.setBorderTop(BorderStyle.THIN);        //上邊框
        style.setBorderBottom(BorderStyle.THIN);    //下邊框
        style.setBorderLeft(BorderStyle.THIN);        //左邊框
        style.setBorderRight(BorderStyle.THIN);        //右邊框
        style.setAlignment(HorizontalAlignment.CENTER);            //水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);    //垂直居中

9、Font

    public Font createCellFont(Workbook wb){
        Font font = wb.createFont();            //設定字型類
        font.setFontHeightInPoints((short) 10);    //設定字號
        font.setFontName("ARIAL");                    //設定字型
        font.setBold(false);                        //設定是否加粗
        font.setColor(IndexedColors.BLACK.index);    //設定字型顏色