簡體   English   中英

用Java創建Excel表的問題

[英]Problems in creating excel sheets with java

我試圖打開一個現有的excel文檔,並試圖創建一個工作表並將數據插入單元格中。 當我在eclipse中編譯我的代碼時,我沒有收到任何錯誤,但是當我運行我的代碼時,它不會影響excel文檔。

這是我的代碼

import java.io.*;
import java.io.FileInputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JFrame;
import javax.swing.JButton;
public class test{
 test()
{
    JFrame f = new JFrame("Pay Slip Generator");
    f.setVisible(true);
    f.setSize(500, 300);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setLayout( new FlowLayout() );
    JButton choose_file = new JButton("choose file");
    f.add(choose_file);
    choose_file.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ae){
             JFileChooser fileopen = new JFileChooser();
                FileFilter filter = new FileNameExtensionFilter("c files", "c");
                fileopen.addChoosableFileFilter(filter);
                int ret = fileopen.showDialog(null, "Open file");
                if (ret == JFileChooser.APPROVE_OPTION) {
                  File file = fileopen.getSelectedFile();
                  String path = file.getAbsolutePath();
                  System.out.println(path);
                  try
                  {
                  FileInputStream fis = new FileInputStream(path);
                  HSSFWorkbook wb = new HSSFWorkbook(fis);
                  int no_sheets = wb.getNumberOfSheets();
                  System.out.println(no_sheets);
                  HSSFSheet sheet = wb.createSheet("test");
                  HSSFRow row = sheet.createRow(10);
                  HSSFCell cell = row.createCell(10);
                  cell.setCellValue("Hello");
                  fis.close();

                  }
                  catch(Exception e)
                  {
                      e.printStackTrace();
                  }
        }
    }
    });

    }
public static void main(String args[])throws IOException
{
    new test();

}

期待得到答復,謝謝。

它沒有影響,因為您沒有將數據寫回到Excel。 cell.setCellValue("Hello");之后插入以下行:

FileOutputStream out = new FileOutputStream(new File(path));
    wb.write(out);
    wb.close();
   out.close();

執行代碼時,請確保您的Excel文件未打開。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM