Apache POI是一套用来处理微软办公文档的java api,可以使用它来处理Excel,word,PowerPoint等等文档。
下载地址:http://poi.apache.org/download.html
解压下载包后我们会看到以下文件:
其中Lib、和ooxml-lib目录里还有一些jar包
新建一个项目,导入所有jar包就可以使用POI提供的功能了
通过以下例子,我们可以创建一个excel文档,并向其中写入数据:
import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
public class POITest {
public static void main(String[] args) {
Workbook wb = new HSSFWorkbook();
FileOutputStream fileOut;
try {
fileOut = new FileOutputStream("D:\\workbook.xls");
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet1 = wb.createSheet("sheet1");
Row row = sheet1.createRow((short)0);
Font font = wb.createFont();
font.setBold(true);
CellStyle style = wb.createCellStyle();
style.setFont(font);
//创建单元格,并写入数据
Cell account = row.createCell(0);
account.setCellStyle(style);
account.setCellValue("账号");
Cell illustrate = row.createCell(1);
illustrate.setCellStyle(style);
illustrate.setCellValue("说明");
Cell attribute = row.createCell(2);
attribute.setCellStyle(style);
attribute.setCellValue("属性");
Cell ciphertext = row.createCell(3);
ciphertext.setCellStyle(style);
ciphertext.setCellValue("密文");
Cell more = row.createCell(4);
more.setCellStyle(style);
more.setCellValue("备注");
wb.write(fileOut);
fileOut.close();
} catch (Exception e) {
}
}
}
运行结果会创建一个workbook.xls的Excel文档,内容如下:
关于Excel的操作,参考官网教程:
http://poi.apache.org/spreadsheet/quick-guide.html