前言
同java POI的学习(一)——Word一致,需要导入jar包。
后面需要用到数据库驱动的jar,小伙伴自行下载咯。
实战
一、如何使用Java创建空excel表?
package com.silin;
import java.io.*;
import org.apache.poi.xssf.usermodel.*;
public class CreateBlankExcel {
public static void main(String[] args) throws Exception {
// 创建空白工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
// 使用特定的名称创建文件系统
FileOutputStream out = new FileOutputStream(new File("createBlankWorkBook.xlsx"));
// 使用file out对象编写操作工作簿
workbook.write(out);
out.close();
System.out.println("createworkbook.xlsx written successfully");
}
}
执行上面示例代码,得到以下结果 -
createworkbook.xlsx written successfully
二、如何使用Java在电子表格中创建不同类型的单元格?
package com.silin;
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 WriteDataToExcel {
public static void main(String[] args) throws Exception {
// 创建空白工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
// 创建一个空白页
XSSFSheet spreadsheet = workbook.createSheet(" Employee Info ");
// 创建行对象
XSSFRow row;
// 需要编写此数据(Object[])
Map empinfo = new TreeMap();
empinfo.put("1", new Object[] { "编号", "姓名", "描述" });
empinfo.put("2", new Object[] { "10010", "李立", "技术经理" });
empinfo.put("3", new Object[] { "10011", "张晓龙", "微信它爹" });
empinfo.put("4", new Object[] { "10012", "王小飞", "技术作家" });
empinfo.put("5", new Object[] { "10013", "库里", "NBA球员" });
empinfo.put("6", new Object[] { "10014", "李双双", "体操运动员" });
// 遍历数据并写入工作表
Set 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);
}
}
// 在文件系统中编写工作簿
FileOutputStream out = new FileOutputStream(new File("Writesheet.xlsx"));
workbook.write(out);
out.close();
System.out.println("Writesheet.xlsx written successfully");
}
}
执行上面示例代码,得到以下结果 -
Writesheet.xlsx written successfully
三、如何使用Java将不同样式应用于电子表格中的单元格?
package com.silin;
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 TypesOfCellsInExcel {
public static void main(String[] args)throws Exception {
//创建一个工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
//创建一个电子表格
XSSFSheet spreadsheet = workbook.createSheet("单元格类型");
XSSFRow row = spreadsheet.createRow((short) 2);
row.createCell(0).setCellValue("单元格类型");
row.createCell(1).setCellValue("单元格值");
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.xlsx written successfully
四、如何使用Java将不同样式应用于电子表格中的单元格?
package com.silin;
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 DifferentStylesToCell {
public static void main(String[] args)throws Exception {
//创建空白的工作薄
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a Spread Sheet
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");
//用于合并单元格的语句
spreadsheet.addMergedRegion(new CellRangeAddress(
1, //first row (0-based)
1, //last row (0-based)
1, //first column (0-based)
4 //last column (0-based)
));
//排列
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);
//单元格内容居中对齐
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);
//右下角对齐
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);
//合理的调整
XSSFCellStyle style4 = workbook.createCellStyle();
style4.setAlignment(XSSFCellStyle.ALIGN_JUSTIFY);
style4.setVerticalAlignment(XSSFCellStyle.VERTICAL_JUSTIFY);
cell.setCellValue("Contents are Justified in Alignment");
cell.setCellStyle(style4);
//边界
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);
//填充颜色
//背景颜色
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);
//前景颜色
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("differentCellStyle.xlsx"));
workbook.write(out);
out.close();
System.out.println("cellstyle.xlsx written successfully");
}
}
执行上面示例代码,得到以下结果 -
cellstyle.xlsx written successfully
五、如何使用Java将字体应用于单元格的内容?
package com.silin;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class DifferentFontsToCell {
public static void main(String[] args) throws Exception {
// 创建一个工作薄
XSSFWorkbook workbook = new XSSFWorkbook();
// 创建一个电子表格
XSSFSheet spreadsheet = workbook.createSheet("Fontstyle");
XSSFRow row = spreadsheet.createRow(2);
// 创建一个新的字体并修改它
XSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 30);
font.setFontName("IMPACT");
font.setItalic(true);
font.setColor(HSSFColor.BRIGHT_GREEN.index);
// 设置字体样式
XSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
// 创建一个具有值的单元格并设置其样式。
XSSFCell cell = row.createCell(1);
cell.setCellValue("文字样式~");
cell.setCellStyle(style);
FileOutputStream out = new FileOutputStream(new File("fontstyle.xlsx"));
workbook.write(out);
out.close();
System.out.println("fontstyle.xlsx written successfully");
}
}
执行上面示例代码,得到以下结果 -
fontstyle.xlsx written successfully
六、如何使用Java设置单元格中的文本的方向?
package com.silin;
import java.io.File;
import java.io.FileOutputStream;
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 TextDirectionInCell {
public static void main(String[] args) throws Exception {
// 创建工作薄
XSSFWorkbook workbook = new XSSFWorkbook();
// 创建一个电子表格
XSSFSheet spreadsheet = workbook.createSheet("Text direction");
XSSFRow row = spreadsheet.createRow(2);
XSSFCellStyle myStyle = workbook.createCellStyle();
myStyle.setRotation((short) 0);
XSSFCell cell = row.createCell(1);
cell.setCellValue("0D angle");
cell.setCellStyle(myStyle);
// 30度
myStyle = workbook.createCellStyle();
myStyle.setRotation((short) 30);
cell = row.createCell(3);
cell.setCellValue("30D angle");
cell.setCellStyle(myStyle);
// 90 度
myStyle = workbook.createCellStyle();
myStyle.setRotation((short) 90);
cell = row.createCell(5);
cell.setCellValue("90D angle");
cell.setCellStyle(myStyle);
// 120 度
myStyle = workbook.createCellStyle();
myStyle.setRotation((short) 120);
cell = row.createCell(7);
cell.setCellValue("120D angle");
cell.setCellStyle(myStyle);
// 270 度
myStyle = workbook.createCellStyle();
myStyle.setRotation((short) 270);
cell = row.createCell(9);
cell.setCellValue("270D angle");
cell.setCellStyle(myStyle);
// 360 度
myStyle = workbook.createCellStyle();
myStyle.setRotation((short) 360);
cell = row.createCell(12);
cell.setCellValue("360D angle");
cell.setCellStyle(myStyle);
FileOutputStream out = new FileOutputStream(new File("textdirection.xlsx"));
workbook.write(out);
out.close();
System.out.println("textdirection.xlsx written successfully");
}
}
执行上面示例代码,得到以下结果 -
textdirection.xlsx written successfully
七、如何使用Java向单元格的内容添加超链接?
package com.silin;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.common.usermodel.Hyperlink;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFHyperlink;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class AddHyperlinkToCell {
public static void main(String[] args) throws Exception {
// 创建工作薄
XSSFWorkbook workbook = new XSSFWorkbook();
// 创建一个电子表格
XSSFSheet spreadsheet = workbook.createSheet("Hyperlinks");
XSSFCell cell;
CreationHelper createHelper = workbook.getCreationHelper();
XSSFCellStyle hlinkstyle = workbook.createCellStyle();
XSSFFont hlinkfont = workbook.createFont();
hlinkfont.setUnderline(XSSFFont.U_SINGLE);
hlinkfont.setColor(HSSFColor.BLUE.index);
hlinkstyle.setFont(hlinkfont);
// URL链接
cell = spreadsheet.createRow(1).createCell((short) 1);
cell.setCellValue("URL Link");
XSSFHyperlink link = (XSSFHyperlink) createHelper.createHyperlink(HyperlinkType.URL);
link.setAddress("http://www.yiibai.com/");
cell.setHyperlink((XSSFHyperlink) link);
cell.setCellStyle(hlinkstyle);
// 超链接到当前目录中的文件
cell = spreadsheet.createRow(2).createCell((short) 1);
cell.setCellValue("File Link");
link = (XSSFHyperlink) createHelper.createHyperlink(HyperlinkType.URL);
link.setAddress("cellstyle.xlsx");
cell.setHyperlink(link);
cell.setCellStyle(hlinkstyle);
// 电子邮件链接
cell = spreadsheet.createRow(3).createCell((short) 1);
cell.setCellValue("Email Link");
link = (XSSFHyperlink) createHelper.createHyperlink(HyperlinkType.EMAIL);
link.setAddress("mailto:[email protected]?subject=Hyperlink");
cell.setHyperlink(link);
cell.setCellStyle(hlinkstyle);
FileOutputStream out = new FileOutputStream(new File("addHyperlink.xlsx"));
// 写的内容
workbook.write(out);
out.close();
System.out.println("hyperlink.xlsx written successfully");
}
}
执行上面示例代码,得到以下结果 -
hyperlink.xlsx written successfully
八、如何使用Java设置电子表格的打印区域?
package com.silin;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFPrintSetup;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class SettingPrintAreaToSpreadSheet {
public static void main(String[] args) throws Exception {
// 创建工作薄
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("Print Area");
// 使用索引设置打印区域
workbook.setPrintArea(0, // sheet index
0, // start column
5, // end column
0, // start row
5 // end row
);
// 设置纸张大小
spreadsheet.getPrintSetup().setPaperSize(XSSFPrintSetup.A4_PAPERSIZE);
// 是否设置显示网格线
spreadsheet.setDisplayGridlines(true);
// set print grid lines or not
spreadsheet.setPrintGridlines(true);
FileOutputStream out = new FileOutputStream(new File("printarea.xlsx"));
workbook.write(out);
out.close();
System.out.println("printarea.xlsx written successfully");
}
}
执行上面示例代码,得到以下结果 -
printarea.xlsx written successfully
九、如何使用Java将数据从数据库插入到电子表格中?
在数据库:testdb中,创建一个emp表,其表结构和数据记录如下 -
CREATE TABLE `emp` (
`emp_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(64) NOT NULL DEFAULT '',
`age` tinyint(2) unsigned NOT NULL DEFAULT '0',
`salary` float(10,2) unsigned DEFAULT '0.00',
`dept` varchar(16) DEFAULT NULL,
PRIMARY KEY (`emp_id`)
) ENGINE=InnoDB AUTO_INCREMENT=103 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of emp
-- ----------------------------
INSERT INTO `emp` VALUES ('100', '王大大', '25', '8100.00', '技术');
INSERT INTO `emp` VALUES ('101', ' 李小伟', '38', '1200.00', '市场');
INSERT INTO `emp` VALUES ('102', ' 张方择', '29', '13500.00', '综合');
以下是使用Java将数据从数据库插入到电子表格中的程序。
package com.silin;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
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 InsertDataFromDataBaseToSpreadSheet {
public static void main(String[] args) throws Exception {
//连接到数据库
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb?useSSL=false", "root" , "123456");
//从表emp_tbl获取数据
Statement statement = connect.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM emp");
//创建一个工作薄
XSSFWorkbook workbook = new XSSFWorkbook();
//创建一个电子表格
XSSFSheet spreadsheet = workbook.createSheet("员工数据信息");
XSSFRow row = spreadsheet.createRow(1);
XSSFCell cell;
cell = row.createCell(1);
cell.setCellValue("编号");
cell = row.createCell(2);
cell.setCellValue("姓名");
cell = row.createCell(3);
cell.setCellValue("年龄");
cell = row.createCell(4);
cell.setCellValue("薪水");
cell = row.createCell(5);
cell.setCellValue("部门");
int i = 2;
while(resultSet.next()) {
row = spreadsheet.createRow(i);
cell = row.createCell(1);
cell.setCellValue(resultSet.getInt("emp_id"));
cell = row.createCell(2);
cell.setCellValue(resultSet.getString("name"));
cell = row.createCell(3);
cell.setCellValue(resultSet.getString("age"));
cell = row.createCell(4);
cell.setCellValue(resultSet.getString("salary"));
cell = row.createCell(5);
cell.setCellValue(resultSet.getString("dept"));
i++;
}
FileOutputStream out = new FileOutputStream(
new File("excel_from_database.xlsx"));
workbook.write(out);
out.close();
System.out.println("excel_from_database.xlsx written successfully");
}
}
执行上面示例代码,得到以下结果 -
excel_from_database.xlsx written successfully