[英]How to remove a row using 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);
}
}
}
查看Shift行的定義:
Shifts rows between startRow and endRow n number of rows. If you use a negative number, it will shift rows up. Code ensures that rows don't wrap around. Calls shiftRows(startRow, endRow, n, false, false);
Additionally shifts merged regions that are completely defined in these rows (ie. merged 2 cells on a row to be shifted).
Specified by: shiftRows(...) in Sheet
Parameters:
startRow the row to start shifting
endRow the row to end shifting
n the number of rows to shift
所以為了刪除第3行,你需要使用startRow = 3
(基於零的索引,所以基本上它是第四行), endRow = sheet.getLastRowNum()
和n = -1
來移動選定的行,即從第4行到最后一行向上排1行。
嘗試更好的特殊功能removeRow
此外,XSSFWorkbook使用.xlsx擴展名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.