簡體   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