如果要求是隻刪除單元格內容,但其餘的格式和註釋,如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即可。