Java 如何使用ApachePOI删除xlsx文件中的单元格内容

Java 如何使用ApachePOI删除xlsx文件中的单元格内容,java,apache-poi,Java,Apache Poi,我想删除xlsx文件中的单元格内容。 我的代码: static void RemoveCell(XSSFSheet mySheet)抛出FileNotFoundException、IOException{ int rownum=mySheet.getLastRowNum(); for(int i=0;i

我想删除xlsx文件中的单元格内容。 我的代码:

static void RemoveCell(XSSFSheet mySheet)抛出FileNotFoundException、IOException{
int rownum=mySheet.getLastRowNum();
for(int i=0;i
但它不起作用。
谢谢!

如果要求仅删除单元格内容,但保留格式和注释,如中所述,则以下操作应有效:

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();

 }
}
import org.apache.poi.xssf.usermodel.*;
导入org.apache.poi.ss.usermodel.*;
导入java.io.*;
类ExcelRemoveCellContent{
静态void removeCellContentsColumnA(XSSFSheet)引发异常{
int rownum=sheet.getLastRowNum();
对于(int i=0;i
cell.getCTCell()。请参阅链接以了解其方法

要清除所选单元格中包含的所有内容、格式和注释(全部清除),只需使用

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();

 }
}