java&数据库:POI(三)——写入数据

lzy 814 0

对于数据,通常执行增删查改四种基本操作,今天总结一下增加和修改。

开始用XSSFWorkbook类、XSSFSheet类等,发现写入数据后文件就损坏了,经过Google后发现直接用Workbook、Sheet、Row等类可以实现数据插入。

所以说,POI大坑!

try {
                // TODO add your handling code here:
                String fileName="C:\\Users\\lance\\Desktop\\data.xlsx";
                File file = new File(fileName);
                Workbook workbook = new XSSFWorkbook(new FileInputStream(file));
                Sheet sheet = workbook.getSheetAt(0);
                int x=sheet.getLastRowNum()+1;
                Row newRow = sheet.createRow(x);
                Cell newCell = newRow.createCell(0);
                newCell.setCellValue(t2.getText());
                newCell = newRow.createCell(1);
                newCell.setCellValue(t3.getText());
                newCell = newRow.createCell(2);
                newCell.setCellValue(t4.getText());
                newCell = newRow.createCell(3);
                newCell.setCellValue(t5.getText());
                workbook.write(new FileOutputStream(fileName));
                workbook.close();
                Object[] options ={ "OK" };  //自定义按钮上的文字
                JOptionPane.showOptionDialog(null,"操作成功!", "success",JOptionPane.YES_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); 
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }

这个比较容易,跟增加数据一样,直接对当前的Cell对象使用setCellValue方法即可。

try {
            // TODO add your handling code here:
            String fileName="C:\\Users\\lance\\Desktop\\data.xlsx";
            File file = new File(fileName);
            Workbook workbook = new XSSFWorkbook(new FileInputStream(file));
            Sheet SPJ = workbook.getSheetAt(1);
            for(Row row:SPJ)
            {
                if(row.getCell(0).getStringCellValue().equals(t11.getText()))
                {
                    row.getCell(3).setCellType(CellType.STRING);
                    int x=Integer.parseInt(row.getCell(3).getStringCellValue());
                    row.getCell(3).setCellValue(new String((int)(1.1*x)+""));
                }
            }
            
            workbook.write(new FileOutputStream(fileName));
            workbook.close();
            Object[] options ={ "OK" };  //自定义按钮上的文字
                JOptionPane.showOptionDialog(null,"修改成功!", "success",JOptionPane.YES_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); 
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

发表评论 取消回复
表情 图片 链接 代码

分享