繁体   English   中英

用Java创建Excel文件

[英]Create Excel file in Java

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

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

//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("sankumarsingh@gmail.com");

            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);
        }
    }
}

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

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

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

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

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();
    }
}

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

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

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

创建 Excel - 从模板创建 Excel

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

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

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

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

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

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

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

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

font.setBoldweight(Font.BOLDWEIGHT_BOLD);

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

我已经创建了 API“generator-excel”来创建一个 Excel 文件,在依赖项下面:

<dependency>
  <groupId>com.github.bld-commons.excel</groupId>
  <artifactId>generator-excel</artifactId>
  <version>3.1.0</version>
</dependency>

这个库可以通过一系列的注释来配置样式、功能、图表、数据透视表等。
您可以通过带或不带参数的查询从数据源获取数据来写入行。
下面举个例子来开发

  1. 我创建了 2 个代表表格行的类。
  2.  package bld.generator.report.junit.entity; import java.util.Date; import org.apache.poi.ss.usermodel.HorizontalAlignment; import bld.generator.report.excel.RowSheet; import bld.generator.report.excel.annotation.ExcelCellLayout; import bld.generator.report.excel.annotation.ExcelColumn; import bld.generator.report.excel.annotation.ExcelDate; import bld.generator.report.excel.annotation.ExcelImage; import bld.generator.report.excel.annotation.ExcelRowHeight; @ExcelRowHeight(height = 3) public class UtenteRow implements RowSheet { @ExcelColumn(columnName = "Id", indexColumn = 0) @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT) private Integer idUtente; @ExcelColumn(columnName = "Nome", indexColumn = 2) @ExcelCellLayout private String nome; @ExcelColumn(columnName = "Cognome", indexColumn = 1) @ExcelCellLayout private String cognome; @ExcelColumn(columnName = "Data di nascita", indexColumn = 3) @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.CENTER) @ExcelDate private Date dataNascita; @ExcelColumn(columnName = "Immagine", indexColumn = 4) @ExcelCellLayout @ExcelImage(resizeHeight = 0.7, resizeWidth = 0.6) private byte[] image; @ExcelColumn(columnName = "Path", indexColumn = 5) @ExcelCellLayout @ExcelImage(resizeHeight = 0.7, resizeWidth = 0.6) private String path; public UtenteRow() { } public UtenteRow(Integer idUtente, String nome, String cognome, Date dataNascita) { super(); this.idUtente = idUtente; this.nome = nome; this.cognome = cognome; this.dataNascita = dataNascita; } public Integer getIdUtente() { return idUtente; } public void setIdUtente(Integer idUtente) { this.idUtente = idUtente; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getCognome() { return cognome; } public void setCognome(String cognome) { this.cognome = cognome; } public Date getDataNascita() { return dataNascita; } public void setDataNascita(Date dataNascita) { this.dataNascita = dataNascita; } public byte[] getImage() { return image; } public String getPath() { return path; } public void setImage(byte[] image) { this.image = image; } public void setPath(String path) { this.path = path; } }

     package bld.generator.report.junit.entity; import org.apache.poi.ss.usermodel.DataConsolidateFunction; import org.apache.poi.ss.usermodel.HorizontalAlignment; import bld.generator.report.excel.RowSheet; import bld.generator.report.excel.annotation.ExcelCellLayout; import bld.generator.report.excel.annotation.ExcelColumn; import bld.generator.report.excel.annotation.ExcelFont; import bld.generator.report.excel.annotation.ExcelSubtotal; import bld.generator.report.excel.annotation.ExcelSubtotals; @ExcelSubtotals(labelTotalGroup = "Total",endLabel = "total") public class SalaryRow implements RowSheet { @ExcelColumn(columnName = "Name", indexColumn = 0) @ExcelCellLayout private String name; @ExcelColumn(columnName = "Amount", indexColumn = 1) @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT) @ExcelSubtotal(dataConsolidateFunction = DataConsolidateFunction.SUM,excelCellLayout = @ExcelCellLayout(horizontalAlignment = HorizontalAlignment.RIGHT,font=@ExcelFont(bold = true))) private Double amount; public SalaryRow() { super(); } public SalaryRow(String name, Double amount) { super(); this.name = name; this.amount = amount; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getAmount() { return amount; } public void setAmount(Double amount) { this.amount = amount; } }
  3. 我创建了 2 个代表工作表的类。
  4.  package bld.generator.report.junit.entity; import javax.validation.constraints.Size; import bld.generator.report.excel.QuerySheetData; import bld.generator.report.excel.annotation.ExcelHeaderLayout; import bld.generator.report.excel.annotation.ExcelMarginSheet; import bld.generator.report.excel.annotation.ExcelQuery; import bld.generator.report.excel.annotation.ExcelSheetLayout; @ExcelSheetLayout @ExcelHeaderLayout @ExcelMarginSheet(bottom = 1.5, left = 1.5, right = 1.5, top = 1.5) @ExcelQuery(select = "SELECT id_utente, nome, cognome, data_nascita,image,path " + "FROM utente " + "WHERE cognome=:cognome " + "order by cognome,nome") public class UtenteSheet extends QuerySheetData<UtenteRow> { public UtenteSheet(@Size(max = 31) String sheetName) { super(sheetName); } }

     package bld.generator.report.junit.entity; import javax.validation.constraints.Size; import bld.generator.report.excel.SheetData; import bld.generator.report.excel.annotation.ExcelHeaderLayout; import bld.generator.report.excel.annotation.ExcelMarginSheet; import bld.generator.report.excel.annotation.ExcelSheetLayout; @ExcelSheetLayout @ExcelHeaderLayout @ExcelMarginSheet(bottom = 1.5,left = 1.5,right = 1.5,top = 1.5) public class SalarySheet extends SheetData<SalaryRow> { public SalarySheet(@Size(max = 31) String sheetName) { super(sheetName); } }
  5. 类测试,在测试功能中有另外的表
  6. package bld.generator.report.junit; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.EnableTransactionManagement; import bld.generator.report.excel.BaseSheet; import bld.generator.report.excel.GenerateExcel; import bld.generator.report.excel.data.ReportExcel; import bld.generator.report.junit.entity.AutoreLibriSheet; import bld.generator.report.junit.entity.CasaEditrice; import bld.generator.report.junit.entity.GenereSheet; import bld.generator.report.junit.entity.SalaryRow; import bld.generator.report.junit.entity.SalarySheet; import bld.generator.report.junit.entity.TotaleAutoreLibriRow; import bld.generator.report.junit.entity.TotaleAutoreLibriSheet; import bld.generator.report.junit.entity.UtenteSheet; import bld.generator.report.utils.ExcelUtils; /** * The Class ReportTest. */ @RunWith(SpringRunner.class) @SpringBootTest @ConfigurationProperties @ComponentScan(basePackages = {"bld.generator","bld.read"}) @EnableTransactionManagement public class ReportTestJpa { /** The Constant PATH_FILE. */ private static final String PATH_FILE = "/mnt/report/"; /** The generate excel. */ @Autowired private GenerateExcel generateExcel; /** * Sets the up. * * @throws Exception the exception */ @Before public void setUp() throws Exception { } /** * Test. * * @throws Exception the exception */ @Test public void test() throws Exception { List<BaseSheet> listBaseSheet = new ArrayList<>(); UtenteSheet utenteSheet=new UtenteSheet("Utente"); utenteSheet.getMapParameters().put("cognome", "Rossi"); listBaseSheet.add(utenteSheet); CasaEditrice casaEditrice = new CasaEditrice("Casa Editrice","Mondadori", new GregorianCalendar(1955, Calendar.MAY, 10), "Roma", "/home/francesco/Documents/git-project/dev-excel/linux.jpg","Drammatico"); listBaseSheet.add(casaEditrice); AutoreLibriSheet autoreLibriSheet = new AutoreLibriSheet("Libri d'autore","Test label"); TotaleAutoreLibriSheet totaleAutoreLibriSheet=new TotaleAutoreLibriSheet(); totaleAutoreLibriSheet.getListRowSheet().add(new TotaleAutoreLibriRow("Totale")); autoreLibriSheet.setSheetFunctionsTotal(totaleAutoreLibriSheet); listBaseSheet.add(autoreLibriSheet); GenereSheet genereSheet=new GenereSheet("Genere"); listBaseSheet.add(genereSheet); SalarySheet salarySheet=new SalarySheet("salary"); salarySheet.getListRowSheet().add(new SalaryRow("a",2.0)); salarySheet.getListRowSheet().add(new SalaryRow("a",2.0)); salarySheet.getListRowSheet().add(new SalaryRow("a",2.0)); salarySheet.getListRowSheet().add(new SalaryRow("a",2.0)); salarySheet.getListRowSheet().add(new SalaryRow("c",1.0)); salarySheet.getListRowSheet().add(new SalaryRow("c",1.0)); salarySheet.getListRowSheet().add(new SalaryRow("c",1.0)); salarySheet.getListRowSheet().add(new SalaryRow("c",1.0)); listBaseSheet.add(salarySheet); ReportExcel excel = new ReportExcel("Mondadori JPA", listBaseSheet); byte[] byteReport = this.generateExcel.createFileXlsx(excel); ExcelUtils.writeToFile(PATH_FILE,excel.getTitle(), ".xlsx", byteReport); } }
  7. 应用程序yaml
  8.  logging: level: root: WARN org: springframework: web: DEBUG hibernate: ERROR spring: datasource: url: jdbc:postgresql://localhost:5432/excel_db username: ${EXCEL_USER_DB} password: ${EXCEL_PASSWORD_DB} jpa: show-sql: true properties: hibernate: default_schema: public jdbc: lob: non_contextual_creation: true format_sql: true ddl-auto: auto database-platform: org.hibernate.dialect.PostgreSQLDialect generate-ddl: true

在github上的项目链接下面:

我个人使用 IntelliJ IDEA,那里的事情有点复杂……我想。

因此,如果您想创建扩展名为 .CSV 、 .XLSX 、 .XLS 的 Excel 文件,您必须下载 Apache Poi(最新版本)。 https://www.apache.org/dyn/closer.lua/poi/release/bin/poi-bin-5.1.0-20211024.zip

之后,您必须创建一个 MAVEN 项目,并且必须在 pom.xml 中添加一些依赖项。 https://www.tutorialspoint.com/maven/maven_external_dependencies.htm

你去吧。 它对我有用,希望你会满意!

最好的问候,塔拉迪加RS6

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM