使用Apache POI用Java写入Excel文件
在本文中,我们将介绍如何使用Apache POI库以Java格式写入Excel文件。如果必须阅读Java中的Excel文件,则可以查看此文章使用Apache POI阅读Java中的Excel文件
Apache POI
Apache POI是用于Microsoft文档的Java API。使用Apache POI,我们可以使用Java读写MS Excel文件。此外,我们可以使用Java读写MS Word和MS PowerPoint文件。
Apache POI支持读取OLE2文件和Office Open XML标准(OOXML)文件。
OLE2文件包括大多数Microsoft Office文件,例如XLS,DOC和PPT以及基于MFC序列化API的文件格式。
Office OpenXML Format是在Microsoft Office 2007和2008中发现的基于新标准的XML文件格式。其中包括XLSX,DOCX和PPTX。
这意味着Apache POI支持编写.xls格式的excel文件以及.xlsx格式的excel文件。
Apache POI的Maven依赖关系
要使用Apache POI写入excel文件,我们需要添加以下依赖项。
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.0.1</version> </dependency>
这种依赖性增加了以下罐子
poi-ooxml-4.0.1.jar poi-4.0.1.jar poi-ooxml-schemas-4.0.1.jar curvesapi-1.05.jar commons-compress-1.18.jar commons-math3-3.6.1.jar commons-collections4-4.2.jar xmlbeans-3.0.2.jar
在这里请注意poi-4.0.1.jar具有用于处理旧Excel格式(.xls)的类
poi-ooxml-4.0.1.jar具有使用较新的excel格式(.xlsx)的类。 Apache POI 4.0.1需要Java 8或者更高版本。
用于编写Excel文件的Apache POI类
以下部分概述了用于使用Apache POI用Java写入excel文件的类。
Apache POI库为两种Excel电子表格格式提供了两种实现
HSSF –这是用于早期excel格式(.xls)的纯Java实现。此实现中的类通常具有HSSF前缀,例如HSSFWorkBook,HSSFSheet。
XSSF –它是xslx文件格式(OOXML)的纯Java实现。此实现中的类通常具有XSSF前缀,例如XSSFWorkBook,XSSFSheet。
SS –这是一个在HSSF和XSSF之上构建的程序包,它使用通用API为两种格式提供通用支持。我们应该尝试使用此程序包中的类以获得更好的兼容性。
使用excel文件时,通常的进度是
有与此进度相对应的界面
org.apache.poi.ss.usermodel.Workbook – Excel工作簿的高级表示形式。这是大多数用户正在阅读或者编写工作簿时构造的第一个对象。它也是创建新图纸的顶层对象。
org.apache.poi.ss.usermodel.Sheet-Excel工作表的高级表示。工作表是工作簿中的中心结构。
org.apache.poi.ss.usermodel.Row-电子表格行的高级表示。
org.apache.poi.ss.usermodel.Cell –电子表格行中单元格的高级表示形式。单元格可以是数字的,基于公式的或者基于字符串的(文本)。
为了创建工作簿,使用了WorkbookFactory类。
- org.apache.poi.ss.usermodel.WorkbookFactory –用于通过从提供的输入中自动检测来创建适当种类的工作簿(HSSFWorkbook或者XSSFWorkbook)的工厂。
使用Apache POI示例以Java编写Excel文件
对于该示例,有一个Employee类,其字段为firstName,lastName,department和DOB。使用这些字段,数据每行4列写入excel文件。
员工阶层
public class Employee {
private String firstName;
private String lastName;
private String department;
private Date dob;
public Employee(String firstName, String lastName, String department, Date dob) {
this.firstName = firstName;
this.lastName = lastName;
this.department = department;
this.dob = dob;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
@Override
public String toString() {
return getFirstName() + " " + getLastName() + " " + getDepartment() + " " + getDob();
}
}
跟随Java类从Employee对象的字段中检索数据,并将其写入Excel工作表。
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class WriteExcel {
private static final String EXCEL_FILE_PATH="F:\theitroad\Java\Java Programs\Java IO\Employee.xlsx";
public static void main(String[] args) {
WriteExcel writeExcel = new WriteExcel();
writeExcel.writeExcelFile(EXCEL_FILE_PATH, WriteExcel.getEmployees());
}
public void writeExcelFile(String excelFilePath, List<Employee> employees) {
final String[] header= {"First Name", "Last Name", "Department", "DOB"};
Workbook workbook = null;
// Excel with .xslx extension
workbook = new XSSFWorkbook();
// For .xls extension HSSF workbook can be created
//workbook = new HSSFWorkbook();
// Creating sheet with in the workbook
Sheet sheet = workbook.createSheet("Employees");
/*Font and style For Header*/
Font font = workbook.createFont();
font.setFontName("VERDANA");
font.setColor(IndexedColors.CORNFLOWER_BLUE.getIndex());
font.setBold(true);
CellStyle style = workbook.createCellStyle();
style.setFont(font);
style.setWrapText(true);
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setFillForegroundColor(IndexedColors.LIGHT_TURQUOISE.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderTop(BorderStyle.THIN);
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
Row row = sheet.createRow(0);
// Writing header to excel
for(int i = 0; i < header.length; i++) {
// each column 20 characters wide
sheet.setColumnWidth(i, 20*256);
Cell cell = row.createCell(i);
cell.setCellValue(header[i]);
cell.setCellStyle(style);
}
// Header styling ends
//Preparing column data for each row
CellStyle dateStyle = workbook.createCellStyle();
// Setting format For the date column
dateStyle.setDataFormat(workbook.getCreationHelper()
.createDataFormat().getFormat("dd/MM/yyyy"));
int rowNum = 1;
for(Employee emp : employees) {
// create new row
row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(emp.getFirstName());
row.createCell(1).setCellValue(emp.getLastName());
row.createCell(2).setCellValue(emp.getDepartment());
Cell cell = row.createCell(3);
cell.setCellValue(emp.getDob());
cell.setCellStyle(dateStyle);
}
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(excelFilePath);
// Writing to excel sheet
workbook.write(outputStream);
} catch (IOException exp) {
// TODO Auto-generated catch block
exp.printStackTrace();
}finally {
if(outputStream != null) {
try {
outputStream.close();
workbook.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
// Method to get list of employees
private static List<Employee> getEmployees(){
List<Employee> employees = new ArrayList<Employee>();
Calendar dob = Calendar.getInstance();
// Month is 0 based
dob.set(1990,10,12); //12-Nov-1990
employees.add(new Employee("John", "Emerson", "Technology", dob.getTime()));
dob.set(1960, 04, 07);
employees.add(new Employee("Shelly", "Mcarthy", "HR", dob.getTime()));
dob.set(1992, 02, 03);
employees.add(new Employee("Tom", "Cevor", "Finance", dob.getTime()));
return employees;
}
}
运行此程序将创建excel表格。

