用Java创建Excel文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1176080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:32:34  来源:igfitidea点击:

Create Excel file in Java

javaexceljexcelapi

提问by

I want to create an Excel file and write data just like writing a text file with Java. I tried to change file extension from .txtto .xls. But I want to bold letters in the Excel file. How can I do that?

我想创建一个 Excel 文件并写入数据,就像用 Java 编写文本文件一样。我试图文件扩展名从改变.txt.xls。但我想在 Excel 文件中加粗字母。我怎样才能做到这一点?

I have tried using the JXL API, but every time I have to create a label I want add no label. Can't O edit row and column of the table?

我曾尝试使用 JXL API,但每次必须创建标签时,我都不想添加标签。不能编辑表格的行和列吗?

回答by huseyint

You can use Apache POIfor creating native binary xls files.

您可以使用Apache POI创建本机二进制 xls 文件。

Or you can use JExcelApiwhich is another, and somewhat light-weight as far as I can remember, Java library for Excel.

或者您可以使用JExcelApi,据我所知,它是另一种轻量级的 Excel Java 库。

回答by aberrant80

Changing the extension of a file does notin any way change its contents. The extension is just a label.

更改文件的扩展名不会以任何方式更改其内容。扩展名只是一个标签。

If you want to work with Excel spreadsheets using Java, read up on the Apache POIlibrary.

如果您想使用 Java 处理 Excel 电子表格,请阅读Apache POI库。

回答by alepuzio

I used also JXLS: it receives the data as a Map and a template EXCEL with the correct syntax and return the file correctly populated. The data in every cell must be a JavaBeanwith visibility public.

我还使用了JXLS:它接收数据作为 Map 和具有正确语法的模板 EXCEL 并返回正确填充的文件。每个单元格中的数据必须是具有public可见性的JavaBean

It not worws if you must insert data in more than 1 sheet: in this case I used POI.

如果您必须在 1 张以上的工作表中插入数据,那就不行了:在这种情况下,我使用了POI

回答by Thorbj?rn Ravn Andersen

Flat files do not allow providing meta information.

平面文件不允许提供元信息。

I would suggest writing out a HTML table containing the information you need, and let Excel read it instead. You can then use <b> tags to do what you ask for.

我建议写出一个包含您需要的信息的 HTML 表格,然后让 Excel 读取它。然后您可以使用 <b> 标签来完成您的要求。

回答by Brian Agnew

To create a spreadsheet and format a cell using POI, see the Working with Fontsexample, and use:

要使用POI创建电子表格和格式化单元格,请参阅使用字体示例,并使用:

font.setBoldweight(Font.BOLDWEIGHT_BOLD);

POI works very well. There are some things you can't do (e.g. create VBA macros), but it'll read/write spreadsheets with macros, so you can create a suitable template sheet, read it and manipulate it with POI, and then write it out.

POI 工作得很好。有些事情你不能做(例如创建 VBA 宏),但它会用宏读/写电子表格,所以你可以创建一个合适的模板表,用 POI 读取和操作它,然后把它写出来。

回答by root

Fair warning about Apache POI's Excel generation... (I know this is an old post, but it's important in case someone looks this up again like I just did)

关于 Apache POI 的 Excel 生成的公平警告......(我知道这是一篇旧帖子,但如果有人像我刚才那样再次查找它很重要)

It had a memory leak issue, which supposedly was solved by 2006, but which people quite recently have still been experiencing. If you want to automate generating a large amount of excel (i.e., if you want to generate a single, large file, a large number of small files, or both), I'd recommend using a different API. Either that, or increasing the JVM stack size to preposterous proportions, and maybe looking into interning strings if you know you won't actually be working with many different strings (although, of course, interning strings means that if you have a large number of different strings, you'll have an entirely different program-crashing memory problem. So, consider that before you go that route).

它有一个内存泄漏问题,据说在 2006 年就解决了,但人们最近仍在经历这个问题。如果您想自动生成大量 excel(即,如果您想生成单个大文件、大量小文件或两者),我建议使用不同的 API。要么,要么将 JVM 堆栈大小增加到荒谬的比例,如果您知道实际上不会使用许多不同的字符串,则可能会查看实习字符串(当然,实习字符串意味着如果您有大量不同的字符串,你会有一个完全不同的程序崩溃内存问题。所以,在你走那条路之前考虑一下)。

回答by Sankumarsingh

//Find jar from here "http://poi.apache.org/download.html"
import  java.io.*;
import  org.apache.poi.hssf.usermodel.HSSFSheet;
import  org.apache.poi.hssf.usermodel.HSSFWorkbook;
import  org.apache.poi.hssf.usermodel.HSSFRow;

public class CreateExlFile{
    public static void main(String[]args) {
        try {
            String filename = "C:/NewExcelFile.xls" ;
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("FirstSheet");  

            HSSFRow rowhead = sheet.createRow((short)0);
            rowhead.createCell(0).setCellValue("No.");
            rowhead.createCell(1).setCellValue("Name");
            rowhead.createCell(2).setCellValue("Address");
            rowhead.createCell(3).setCellValue("Email");

            HSSFRow row = sheet.createRow((short)1);
            row.createCell(0).setCellValue("1");
            row.createCell(1).setCellValue("Sankumarsingh");
            row.createCell(2).setCellValue("India");
            row.createCell(3).setCellValue("[email protected]");

            FileOutputStream fileOut = new FileOutputStream(filename);
            workbook.write(fileOut);
            fileOut.close();
            workbook.close();
            System.out.println("Your excel file has been generated!");

        } catch ( Exception ex ) {
            System.out.println(ex);
        }
    }
}

回答by Erieze Lagera

I've created an API to create an Excel file more easier.

我创建了一个 API 来更轻松地创建 Excel 文件。

Create Excel - Creating Excel from Template

创建 Excel - 从模板创建 Excel

Just set the required values upon instantiation then invoke execute(), it will be created based on your desired output directory.

只需在实例化时设置所需的值,然后调用 execute(),它将根据您所需的输出目录创建。

But before you use this, you must have an Excel Template which will be use as a template of the newly created Excel file.

但是在使用它之前,您必须有一个 Excel 模板,它将用作新创建的 Excel 文件的模板。

Also, you need Apache POIin your project's class path.

此外,您需要在项目的类路径中使用Apache POI

回答by satender

File fileName = new File(".....\Fund.xlsx");

public static void createWorkbook(File fileName) throws IOException {
    try {
        FileOutputStream fos = new FileOutputStream(fileName);
        XSSFWorkbook  workbook = new XSSFWorkbook();            

        XSSFSheet sheet = workbook.createSheet("fund");  

        Row row = sheet.createRow(0);   
        Cell cell0 = row.createCell(0);
        cell0.setCellValue("Nav Value");

        Cell cell1 = row.createCell(1);

        cell1.setCellValue("Amount Change");       

        Cell cell2 = row.createCell(2);
        cell2.setCellValue("Percent Change");

        workbook.write(fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}