📜  如何使用Java将数据写入Excel工作表?

📅  最后修改于: 2022-05-13 01:54:26.476000             🧑  作者: Mango

如何使用Java将数据写入Excel工作表?

处理文件是任何编程语言的重要组成部分。 Java提供了各种内置方法来创建、读取、更新和删除文件。这些方法由Java.io包中的File类提供。为了执行文件操作, Java使用流类。

要使用Java在 excel 表格中进行操作,使用CSV文件会很方便,因为 CSV 文件可以轻松地与 Microsoft Excel、Google 电子表格和几乎所有其他可用的电子表格一起使用。

使用 poi 将数据写入 Excel 工作表本身:

1.创建一个空白工作簿。

XSSFWorkbook workbook = new XSSFWorkbook();

2.创建一个工作表并为其命名。

XSSFSheet spreadsheet = workbook.createSheet(" Student Data ");

3.创建一行

Row row = sheet.createRow(rownum++);

4.添加单元格 表。

5.重复步骤3 和 4 写入完整数据。

先决条件:在Java程序的构建路径中添加从Apache POI下载站点下载的所有jar文件。

例子:

Java
// Java program to write data in excel sheet using java code
  
import java.io.File;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
  
public class WriteDataToExcel {
  
    // any exceptions need to be caught
    public static void main(String[] args) throws Exception
    {
        // workbook object
        XSSFWorkbook workbook = new XSSFWorkbook();
  
        // spreadsheet object
        XSSFSheet spreadsheet
            = workbook.createSheet(" Student Data ");
  
        // creating a row object
        XSSFRow row;
  
        // This data needs to be written (Object[])
        Map studentData
            = new TreeMap();
  
        studentData.put(
            "1",
            new Object[] { "Roll No", "NAME", "Year" });
  
        studentData.put("2", new Object[] { "128", "Aditya",
                                            "2nd year" });
  
        studentData.put(
            "3",
            new Object[] { "129", "Narayana", "2nd year" });
  
        studentData.put("4", new Object[] { "130", "Mohan",
                                            "2nd year" });
  
        studentData.put("5", new Object[] { "131", "Radha",
                                            "2nd year" });
  
        studentData.put("6", new Object[] { "132", "Gopal",
                                            "2nd year" });
  
        Set keyid = studentData.keySet();
  
        int rowid = 0;
  
        // writing the data into the sheets...
  
        for (String key : keyid) {
  
            row = spreadsheet.createRow(rowid++);
            Object[] objectArr = studentData.get(key);
            int cellid = 0;
  
            for (Object obj : objectArr) {
                Cell cell = row.createCell(cellid++);
                cell.setCellValue((String)obj);
            }
        }
  
        // .xlsx is the format for Excel Sheets...
        // writing the workbook into the file...
        FileOutputStream out = new FileOutputStream(
            new File("C:/savedexcel/GFGsheet.xlsx"));
  
        workbook.write(out);
        out.close();
    }
}


输出: