在arcel java中写一个arraylist

时间:2016-03-18 14:38:09

标签: java excel

我有一个数组列表,并将复选框和文本字段中的所有文本添加到此列表中 我想在excel文件中写这个列表......任何想法?例如

public ArrayList<String> savelist = new ArrayList<>();
age = ageField.getText();
        city = poliField.getText();
        address = AddrField.getText();
        telephone = telField.getText();
     savelist.add("City "+ city);
    savelist.add("Address "+ address);
        savelist.add("Telephone "+ telephone);
    savelist.add("Age "+ age);
        savelist.add("Gender "+ gender);
        savelist.add("Pregnancy "+ prgn);

我找到了以下代码,但我很困惑

HSSFWorkbook workbook = new HSSFWorkbook();
      HSSFSheet  Sheet  = workbook.createSheet();
for (int i=0; i<mylist.size(); i++) {
 HSSFRow  Row  = Sheet.createRow(i);
   Row.createCell(0).setCellValue( list1.get(i) );
   Row.createCell(1).setCellValue( list2.get(i) );
   Row.createCell(2).setCellValue( list3.get(i) );
} 

1 个答案:

答案 0 :(得分:1)

我找到了解决方案! ^ _ ^

try {

        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("testinsert");
        HSSFRow rowhead = sheet.createRow((short) 0);
        rowhead.createCell((short) 0).setCellValue("Results");

        int i = 1;
        FileOutputStream fileOut = null;
        File sv = null;
        JFileChooser chooser = new JFileChooser();
      FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel Files", "xls", "csv");
        chooser.setFileFilter(filter);
        chooser.addChoosableFileFilter(filter);

        int returnVal = chooser.showSaveDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {

            sv = chooser.getSelectedFile();

            fileOut = new FileOutputStream(sv);

        } else {

            return;
        }

        while ( i<savelist.size()) {
            HSSFRow row = sheet.createRow((short) i);
            row.createCell((short) 0).setCellValue(savelist.get(i) );
            row.createCell((short) 1).setCellValue(savelist.get(i) );
            row.createCell((short) 2).setCellValue(savelist.get(i) );

            i++;

        }

        workbook.write(fileOut);
        fileOut.close();


    } catch (IOException ex) {
        Logger.getLogger(Diagnosis.class.getName()).log(Level.SEVERE, null, ex);
    }

    JOptionPane.showMessageDialog(null, "data exported");

唯一的问题是,当我保存文件时,我必须手动更改扩展名......:\