我已经阅读了与我类似的其他问题,但我错过了一些内容,因为我的行都没有被删除...经过多次尝试后,我已经结束了以下代码..
我想删除除第1行以外的所有行,这就是计数器从1开始的原因......
//...
FileInputStream file = new FileInputStream(new File("E:\\products.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
for(int i=1; i<= sheet.getLastRowNum(); i++){
Row row = sheet.getRow(i);
deleteRow(sheet, row);
}
file.close();
FileOutputStream outFile = new FileOutputStream(new File("E:\\products.xls"));
workbook.write(outFile);
outFile.close();
//...
//The delete method...
private void deleteRow(HSSFSheet sheet, Row row) {
int lastRowNum = sheet.getLastRowNum();
int rowIndex = row.getRowNum();
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);
System.out.println("Deleting.... ");
}
}
}
我没有收到任何错误,但没有删除任何行。
更新
如下所述,我没有保存文件...我更新了上面的代码,现在我保存了它!但是,我的一些行被删除而不是所有行... 任何想法为什么会发生这种情况?
答案 0 :(得分:2)
Yuor代码完美无缺,只缺少一件事:将结果写入文件......
wb.write(new FileOutputStream(new File("E:\\products.xls")));
完整的工作示例:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
public class Main {
public Main() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) throws IOException {
FileInputStream file = null;
HSSFWorkbook wb = null;
FileOutputStream out = null;
try{
file = new FileInputStream(new File("E:\\products.xls"));
wb = new HSSFWorkbook(file);
HSSFSheet sheet = wb.getSheetAt(0);
for(int i=1; i<= sheet.getLastRowNum(); i++){
Row row = sheet.getRow(i);
deleteRow(sheet, row);
}
out = new FileOutputStream(new File("E:\\products.xls"));
wb.write(out);
}
catch(Exception e){}
finally{
if(file!=null)
file.close();
if(out!=null)
out.close();
if(wb!=null)
wb.close();
}
}
public static void deleteRow(HSSFSheet sheet, Row row) {
int lastRowNum = sheet.getLastRowNum();
int rowIndex = row.getRowNum();
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);
System.out.println("Deleting.... ");
}
}
}
}
您的代码中唯一的问题是,它不是您对方法的期望 deleteRow(..)我以这种方式修改了您的方法:
public static void deleteRow(HSSFSheet sheet, Row row) {
int lastRowNum = sheet.getLastRowNum();
if(lastRowNum !=0 && lastRowNum >0){
int rowIndex = row.getRowNum();
Row removingRow = sheet.getRow(rowIndex);
if(removingRow != null){
sheet.removeRow(removingRow);
System.out.println("Deleting.... ");
}
}
}
如果文件中只有一行,则不会删除,如果还有,则删除除第一行以外的所有行。
答案 1 :(得分:0)
你忘了显然保存你的工作簿......
Function Test() As Boolean
Dim X As Integer
X = 5
Return (X = 10)
End Function
答案 2 :(得分:0)
我想你忘了保存更改。