使用Apache POI Java修改现有Excel文件

时间:2017-03-28 20:16:46

标签: java excel apache-poi

所以我在修改excel文件时遇到了问题。我不确定在输出流或什么时我编写目录的方式是错误的,但数据永远不会被修改。我没有收到任何错误,也没有在我的桌面上创建新文件,现有文件保持不变。我知道我的数据正在被修改,因为我的目标是删除以前行中具有相同数据的行。我打印出我的ArrayList,并删除了所有重复的行。请帮忙!顺便在OX X上运行。

public class readInExcel {
static void readExcel() throws IOException
{

    JFileChooser fileChooser = new JFileChooser();

    FileNameExtensionFilter filter = new FileNameExtensionFilter(
    "xls","xlsx");

    fileChooser.setFileFilter(filter);

    fileChooser.setCurrentDirectory(new 
    File(System.getProperty("user.home")));

    int returnVal = fileChooser.showOpenDialog(new JPanel());

    if(returnVal == JFileChooser.APPROVE_OPTION)
    {   
        File OGFile = fileChooser.getSelectedFile();

        String fileName = "user.home.Desktop";

        XSSFWorkbook wb;
        try (InputStream is = new FileInputStream(OGFile)) {
            wb = new XSSFWorkbook(is);
            XSSFSheet sheet = wb.getSheetAt(0);
            ArrayList<String> data = new ArrayList<>();
            Iterator<Row> rowIterator = sheet.iterator();
            //Row row = rowIterator.next();
            XSSFRow currentRow;
            int a = sheet.getPhysicalNumberOfRows();
            int columnIndex = 18;
            for (int rowIndex = 2; rowIndex <= a; rowIndex++)
            {
                Row row = CellUtil.getRow(rowIndex, sheet);
                Cell cell = CellUtil.getCell(row, columnIndex);

              data.contains(cell.getStringCellValue());
                  if(data.contains(cell.getStringCellValue()))
                    if(row != null)
                        sheet.removeRow(row);
                    else
                        data.add(cell.getStringCellValue());
            }
        }

        try (FileOutputStream outFile = new FileOutputStream(new 
        File("user\\home\\Desktop\new.xlsx"))) {
            wb.write(outFile);
        }
    }
}

}

0 个答案:

没有答案