在Java编程中,如何将不同样式应用于Excel中的单元格?
注意:需要访问网址:http://poi.apache.org/download.html , 下载一个Apache POI软件包。这里下载最新版本:poi-bin-3.17-20170915.tar.gz解压并将全部
.jar
文件导入 。
需要导入全部包,如下图所示 -
参考示例:
http://poi.apache.org/spreadsheet/quick-guide.html
以下是使用Java将不同样式应用于Excel中的单元格的程序。
package com.yiibai;
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 {
// Create a Work Book
XSSFWorkbook workbook = new XSSFWorkbook();
// Create a Spread Sheet
XSSFSheet spreadsheet = workbook.createSheet("Fontstyle");
XSSFRow row = spreadsheet.createRow(2);
// Create a new font and alter it
XSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 30);
font.setFontName("IMPACT");
font.setItalic(true);
font.setColor(HSSFColor.BRIGHT_GREEN.index);
// Set font into style
XSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
// Create a cell with a value and set style to it.
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
创建的Excel文件内容,如下所示 -