Apache POI工作簿
此处的术语“Workbook”指的Microsoft Excel文件。本章完成后,您将能够创建新的工作簿,并可以使用Java程序打开现有工作簿。
此处的术语“Workbook”指的Microsoft Excel文件。本章完成后,您将能够创建新的工作簿,并可以使用Java程序打开现有工作簿。
创建空白工作簿
下面简单的程序来创建一个空白Microsoft Excel工作簿。
import java.io.*;
import org.apache.poi.xssf.usermodel.*;
public class CreateWorkBook
{
public static void main(String[] args)throws Exception
{
//Create Blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create file system using specific name
FileOutputStream out = new FileOutputStream(
new File("createworkbook.xlsx"));
//write operation workbook using file out object
workbook.write(out);
out.close();
System.out.println("
createworkbook.xlsx written successfully");
}
}
让我们保存上面的Java代码为CreateWorkBook.java,然后编译并从命令提示符如下执行它:
$javac CreateWorkBook.java
$java CreateWorkBook
如果系统环境配置了POI 库,它会编译和执行,并生成一个名为createworkbook.xlsx 在当前目录下的空白Excel文件并显示在命令提示符处键入以下输出。
createworkbook.xlsx written successfully
打开现有工作簿
使用下面的代码打开现有的工作簿。
import java.io.*;
import org.apache.poi.xssf.usermodel.*;
public class OpenWorkBook
{
public static void main(String args[])throws Exception
{
File file = new File("openworkbook.xlsx");
FileInputStream fIP = new FileInputStream(file);
//Get the workbook instance for XLSX file
XSSFWorkbook workbook = new XSSFWorkbook(fIP);
if(file.isFile() && file.exists())
{
System.out.println(
"openworkbook.xlsx file open successfully.");
}
else
{
System.out.println(
"Error to open openworkbook.xlsx file.");
}
}
}
保存上面的Java代码为OpenWorkBook.java,然后编译并从命令提示符如下执行它:
$javac OpenWorkBook.java
$java OpenWorkBook
这将编译和执行生成以下输出。
openworkbook.xlsx file open successfully.
打开工作簿后,可以进行读取,并在上面写操作。
Apache POI电子表格/Spreadsheet
本章将介绍如何创建一个电子表格,并使用Java操纵它。电子表格是在Excel文件中的页面;它包含具有特定名称的行和列。
读完本章后,将能够创建一个电子表格,并能在其上执行读取操作。
创建电子表格
首先,让我们创建一个使用在前面的章节中讨论的引用的类的电子表格。按照前面的章节中,首先创建一个工作簿,然后我们就可以去,并创建一个表。
下面的代码片段用于创建电子表格。
//Create Blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank spreadsheet
XSSFSheet spreadsheet = workbook.createSheet("Sheet Name");
在电子表格的行
电子表格有一个网格布局。行和列被标识与特定的名称。该列标识字母和行用数字。
下面的代码片段用于创建一个行。
XSSFRow row = spreadsheet.createRow((short)1);
写入到电子表格
让我们考虑雇员数据的一个例子。这里的雇员数据给出以表格形式。
Emp Id | Emp Name | 称号 |
---|---|---|
Tp01 | Gopal | Technical Manager |
TP02 | Manisha | Proof Reader |
Tp03 | Masthan | Technical Writer |
Tp04 | Satish | Technical Writer |
Tp05 | Krishna | Technical Writer |
以下代码是用来写上述数据到电子表格。
import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
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;
public class Writesheet
{
public static void main(String[] args) throws Exception
{
//Create blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet spreadsheet = workbook.createSheet(
" Employee Info ");
//Create row object
XSSFRow row;
//This data needs to be written (Object[])
Map < String, Object[] > empinfo =
new TreeMap < String, Object[] >();
empinfo.put( "1", new Object[] {
"EMP ID", "EMP NAME", "DESIGNATION" });
empinfo.put( "2", new Object[] {
"tp01", "Gopal", "Technical Manager" });
empinfo.put( "3", new Object[] {
"tp02", "Manisha", "Proof Reader" });
empinfo.put( "4", new Object[] {
"tp03", "Masthan", "Technical Writer" });
empinfo.put( "5", new Object[] {
"tp04", "Satish", "Technical Writer" });
empinfo.put( "6", new Object[] {
"tp05", "Krishna", "Technical Writer" });
//Iterate over data and write to sheet
Set < String > keyid = empinfo.keySet();
int rowid = 0;
for (String key : keyid)
{
row = spreadsheet.createRow(rowid++);
Object [] objectArr = empinfo.get(key);
int cellid = 0;
for (Object obj : objectArr)
{
Cell cell = row.createCell(cellid++);
cell.setCellValue((String)obj);
}
}
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(
new File("Writesheet.xlsx"));
workbook.write(out);
out.close();
System.out.println(
"Writesheet.xlsx written successfully" );
}
}
上面的Java代码保存为Writesheet.java,然后并在命令提示符下编译运行,如下所示:
$javac Writesheet.java
$java Writesheet
这将编译和执行来生成一个Excel文件名为Writesheet.xlsx在当前目录中,在命令提示符处键入以下输出。
Writesheet.xlsx written successfully
Writesheet.xlsx文件的内容如下所示。
从电子表格读取数据
让我们考虑上述excel文件命名Writesheet.xslx作为输入文件。注意下面的代码;它是用于从电子表格中读取数据。
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Readsheet
{
static XSSFRow row;
public static void main(String[] args) throws Exception
{
FileInputStream fis = new FileInputStream(
new File("WriteSheet.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet spreadsheet = workbook.getSheetAt(0);
Iterator < Row > rowIterator = spreadsheet.iterator();
while (rowIterator.hasNext())
{
row = (XSSFRow) rowIterator.next();
Iterator < Cell > cellIterator = row.cellIterator();
while ( cellIterator.hasNext())
{
Cell cell = cellIterator.next();
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
System.out.print(
cell.getNumericCellValue() + " \t\t " );
break;
case Cell.CELL_TYPE_STRING:
System.out.print(
cell.getStringCellValue() + " \t\t " );
break;
}
}
System.out.println();
}
fis.close();
}
}
让我们把上面的代码保存在Readsheet.java文件,然后编译并在命令提示符下运行,如下所示:
$javac Readsheet.java
$java Readsheet
如果您的系统环境配置了POI库,它会编译和执行产生在命令提示符处键入以下输出。
EMP ID EMP NAME DESIGNATION
tp01 Gopal Technical Manager
tp02 Manisha Proof Reader
tp03 Masthan Technical Writer
tp04 Satish Technical Writer
tp05 Krishna Technical Writer
Apache POI单元格/Cells
输入到电子表格中的任何数据总是存储在一个单元中。我们使用的行和列的标签来识别单元格。本章介绍了如何使用Java编程操纵单元电子表格的数据。
创建一个单元格
需要创建一个单元之前创建一个行。行是什么?只不过是单元的集合。
下面的代码片段用于创建一个单元格。
//create new workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//create spreadsheet with a name
XSSFSheet spreadsheet = workbook.createSheet("new sheet");
//create first row on a created spreadsheet
XSSFRow row = spreadsheet.createRow(0);
//create first cell on created row
XSSFCell cell = row.createCell(0);
单元格类型
单元格类型指定单元格是否可以包含字符串,数值,或公式。字符串单元不能持有数值和数值单元格无法容纳字符串。下面给出是单元格值和类型的语法。
单元格的值类型 | 类型语法 |
---|---|
Blank cell value | XSSFCell.CELL_TYPE_BLANK |
Boolean cell value | XSSFCell.CELL.TYPE_BOOLEAN |
Error cell value | XSSFCell.CELL_TYPE_ERROR |
Numeric cell value | XSSFCell.CELL_TYPE_NUMERIC |
String cell value | XSSFCell.CELL_TYPE_STRING |
以下代码是用于在电子表格创建不同类型的单元格。
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class TypesofCells
{
public static void main(String[] args)throws Exception
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("cell types");
XSSFRow row = spreadsheet.createRow((short) 2);
row.createCell(0).setCellValue("Type of Cell");
row.createCell(1).setCellValue("cell value");
row = spreadsheet.createRow((short) 3);
row.createCell(0).setCellValue("set cell type BLANK");
row.createCell(1);
row = spreadsheet.createRow((short) 4);
row.createCell(0).setCellValue("set cell type BOOLEAN");
row.createCell(1).setCellValue(true);
row = spreadsheet.createRow((short) 5);
row.createCell(0).setCellValue("set cell type ERROR");
row.createCell(1).setCellValue(XSSFCell.CELL_TYPE_ERROR );
row = spreadsheet.createRow((short) 6);
row.createCell(0).setCellValue("set cell type date");
row.createCell(1).setCellValue(new Date());
row = spreadsheet.createRow((short) 7);
row.createCell(0).setCellValue("set cell type numeric" );
row.createCell(1).setCellValue(20 );
row = spreadsheet.createRow((short) 8);
row.createCell(0).setCellValue("set cell type string");
row.createCell(1).setCellValue("A String");
FileOutputStream out = new FileOutputStream(
new File("typesofcells.xlsx"));
workbook.write(out);
out.close();
System.out.println(
"typesofcells.xlsx written successfully");
}
}
保存上面的代码到一个名为TypesofCells.java文件,编译并从命令提示符如下执行它。
$javac TypesofCells.java
$java TypesofCells
如果您的系统配置了POI库,那么它会编译和执行在当前目录中生成一个名为typesofcells.xlsx的Excel文件,并显示以下输出。
typesofcells.xlsx written successfully
typesofcells.xlsx文件如下所示。
单元格样式
在这里,可以学习如何做单元格格式,并采用不同的风格,如合并相邻的单元格,添加边框,设置单元格对齐方式和填充颜色。
以下代码是使用Java编程用于不同样式应用到单元格。
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CellStyle
{
public static void main(String[] args)throws Exception
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("cellstyle");
XSSFRow row = spreadsheet.createRow((short) 1);
row.setHeight((short) 800);
XSSFCell cell = (XSSFCell) row.createCell((short) 1);
cell.setCellValue("test of merging");
//MEARGING CELLS
//this statement for merging cells
spreadsheet.addMergedRegion(new CellRangeAddress(
1, //first row (0-based)
1, //last row (0-based)
1, //first column (0-based)
4 //last column (0-based)
));
//CELL Alignment
row = spreadsheet.createRow(5);
cell = (XSSFCell) row.createCell(0);
row.setHeight((short) 800);
// Top Left alignment
XSSFCellStyle style1 = workbook.createCellStyle();
spreadsheet.setColumnWidth(0, 8000);
style1.setAlignment(XSSFCellStyle.ALIGN_LEFT);
style1.setVerticalAlignment(XSSFCellStyle.VERTICAL_TOP);
cell.setCellValue("Top Left");
cell.setCellStyle(style1);
row = spreadsheet.createRow(6);
cell = (XSSFCell) row.createCell(1);
row.setHeight((short) 800);
// Center Align Cell Contents
XSSFCellStyle style2 = workbook.createCellStyle();
style2.setAlignment(XSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(
XSSFCellStyle.VERTICAL_CENTER);
cell.setCellValue("Center Aligned");
cell.setCellStyle(style2);
row = spreadsheet.createRow(7);
cell = (XSSFCell) row.createCell(2);
row.setHeight((short) 800);
// Bottom Right alignment
XSSFCellStyle style3 = workbook.createCellStyle();
style3.setAlignment(XSSFCellStyle.ALIGN_RIGHT);
style3.setVerticalAlignment(
XSSFCellStyle.VERTICAL_BOTTOM);
cell.setCellValue("Bottom Right");
cell.setCellStyle(style3);
row = spreadsheet.createRow(8);
cell = (XSSFCell) row.createCell(3);
// Justified Alignment
XSSFCellStyle style4 = workbook.createCellStyle();
style4.setAlignment(XSSFCellStyle.ALIGN_JUSTIFY);
style4.setVerticalAlignment(
XSSFCellStyle.VERTICAL_JUSTIFY);
cell.setCellValue("Contents are Justified in Alignment");
cell.setCellStyle(style4);
//CELL BORDER
row = spreadsheet.createRow((short) 10);
row.setHeight((short) 800);
cell = (XSSFCell) row.createCell((short) 1);
cell.setCellValue("BORDER");
XSSFCellStyle style5 = workbook.createCellStyle();
style5.setBorderBottom(XSSFCellStyle.BORDER_THICK);
style5.setBottomBorderColor(
IndexedColors.BLUE.getIndex());
style5.setBorderLeft(XSSFCellStyle.BORDER_DOUBLE);
style5.setLeftBorderColor(
IndexedColors.GREEN.getIndex());
style5.setBorderRight(XSSFCellStyle.BORDER_HAIR);
style5.setRightBorderColor(
IndexedColors.RED.getIndex());
style5.setBorderTop(XSSFCellStyle.BIG_SPOTS);
style5.setTopBorderColor(
IndexedColors.CORAL.getIndex());
cell.setCellStyle(style5);
//Fill Colors
//background color
row = spreadsheet.createRow((short) 10 );
cell = (XSSFCell) row.createCell((short) 1);
XSSFCellStyle style6 = workbook.createCellStyle();
style6.setFillBackgroundColor(
HSSFColor.LEMON_CHIFFON.index );
style6.setFillPattern(XSSFCellStyle.LESS_DOTS);
style6.setAlignment(XSSFCellStyle.ALIGN_FILL);
spreadsheet.setColumnWidth(1,8000);
cell.setCellValue("FILL BACKGROUNG/FILL PATTERN");
cell.setCellStyle(style6);
//Foreground color
row = spreadsheet.createRow((short) 12);
cell = (XSSFCell) row.createCell((short) 1);
XSSFCellStyle style7=workbook.createCellStyle();
style7.setFillForegroundColor(HSSFColor.BLUE.index);
style7.setFillPattern( XSSFCellStyle.LESS_DOTS);
style7.setAlignment(XSSFCellStyle.ALIGN_FILL);
cell.setCellValue("FILL FOREGROUND/FILL PATTERN");
cell.setCellStyle(style7);
FileOutputStream out = new FileOutputStream(
new File("cellstyle.xlsx"));
workbook.write(out);
out.close();
System.out.println("cellstyle.xlsx written successfully");
}
}
保存上面的代码在一个名为CellStyle.java文件,编译并从命令提示符如下执行它。
$javac CellStyle.java
$java CellStyle
它会生成一个名为cellstyle.xlsx在当前目录中的Excel文件并显示以下输出。
cellstyle.xlsx written successfully
cellstyle.xlsx文件如下所示。
ell.setCellStyle(style7);
FileOutputStream out = new FileOutputStream(
new File(“cellstyle.xlsx”));
workbook.write(out);
out.close();
System.out.println(“cellstyle.xlsx written successfully”);
}
}
保存上面的代码在一个名为CellStyle.java文件,编译并从命令提示符如下执行它。
$javac CellStyle.java
$java CellStyle
它会生成一个名为cellstyle.xlsx在当前目录中的Excel文件并显示以下输出。
cellstyle.xlsx written successfully