2017-07-30 68 views
0

我想刪除xlsx文件中的單元格內容。 我的代碼:如何使用apache POI刪除xlsx文件中的單元格內容

static void RemoveCell(XSSFSheet mySheet) throws FileNotFoundException, IOException { 
    int rownum = mySheet.getLastRowNum(); 
    for (int i = 0; i < rownum; i++) { 
     Row currentRow = mySheet.getRow(i); 
     Cell cell = currentRow.getCell(0); 
     if (cell.getCellType() != Cell.CELL_TYPE_BLANK) { 
      cell.setCellType(Cell.CELL_TYPE_BLANK); 
     } 
    } 
} 

但它不起作用。 謝謝!

回答

1

如果要求是隻刪除單元格內容,但其餘的格式和註釋,如Clear cells of contents or formats描述,那麼下面應該工作:

import org.apache.poi.xssf.usermodel.*; 
import org.apache.poi.ss.usermodel.*; 

import java.io.*; 

class ExcelRemoveCellContent { 

static void removeCellContentsColumnA(XSSFSheet sheet) throws Exception { 
    int rownum = sheet.getLastRowNum(); 
    for (int i = 0; i < rownum+1; i++) { 
    XSSFRow row = sheet.getRow(i); 
    if (row != null) { 
    XSSFCell cell = row.getCell(0); 
    if (cell != null) { 
    if (cell.getCTCell().isSetT()) cell.getCTCell().unsetT(); 
    if (cell.getCTCell().isSetV()) cell.getCTCell().unsetV(); 
    } 
    } 
    } 
} 

public static void main(String[] args) throws Exception{ 

    InputStream inp = new FileInputStream("ExcelRemoveCellContent.xlsx"); 
    Workbook workbook = WorkbookFactory.create(inp); 

    Sheet sheet = workbook.getSheetAt(0); 

    removeCellContentsColumnA((XSSFSheet)sheet); 

    workbook.write(new FileOutputStream("ExcelRemoveCellContent.xlsx")); 
    workbook.close(); 

} 
} 

cell.getCTCell()返回CTCell。查看它的方法的鏈接。

要清除選定單元格中包含的所有內容,格式和註釋(全部清除),只需使用Row.removeCell即可。

相關問題