如何使用Apache POI删除行
我试图删除第三行
这是我根据rgettman,Leo,zibi的评论进行的编辑。谢谢。
public class MainTest { public static void main(String[] args) throws IOException {
FileInputStream file = new FileInputStream(new File("test.xlsx") );
XSSFWorkbook wb = new XSSFWorkbook(file);
XSSFSheet sheet = wb.getSheetAt(0);
sheet.removeRow(sheet.getRow(3));
// sheet.shiftRows(3, 3, -1);
File outWB = new File("testResult.xlsx");
OutputStream out = new FileOutputStream(outWB);
wb.write(out);
out.flush();
out.close();
System.exit(0);
}
}
但这会删除一行中的值,但不会删除该行
回答:
如果您使用的是XLS文件(不是XLSX),则应使用HSSFWorkbook。我刚刚测试了以下解决方案,并且一切正常:
File file = new File(....); FileInputStream fis = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sheet = wb.getSheetAt(0);
sheet.shiftRows(3, 3, -1);
File outWB = new File(.....);
OutputStream out = new FileOutputStream(outWB);
wb.write(out);
out.flush();
out.close();
甚至更好地使用Workbook工厂,该工厂会为您进行识别:
Workbook wb = WorkbookFactory.create(file); Sheet sheet = wb.getSheetAt(0);
sheet.shiftRows(3, 3, -1);
在下面,您可以找到执行行删除的功能,该功能可以在xls和xlsx中使用(已测试;))。
Workbook wb = WorkbookFactory.create(file);Sheet sheet = wb.getSheetAt(0);
removeRow(sheet, 2);
File outWB = new File(...);
OutputStream out = new FileOutputStream(outWB);
wb.write(out);
out.flush();
out.close();
public static void removeRow(Sheet sheet, int rowIndex) {
int lastRowNum = sheet.getLastRowNum();
if (rowIndex >= 0 && rowIndex < lastRowNum) {
sheet.shiftRows(rowIndex + 1, lastRowNum, -1);
}
if (rowIndex == lastRowNum) {
Row removingRow = sheet.getRow(rowIndex);
if (removingRow != null) {
sheet.removeRow(removingRow);
}
}
}
以上是 如何使用Apache POI删除行 的全部内容, 来源链接: utcz.com/qa/417029.html