设置字体和单元格的颜色代码如下:
package excle;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
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 ExcleUnit {
public static XSSFSheet ExcelSheet;
public static XSSFWorkbook ExcelBook;
public static XSSFRow Row;
public static HSSFCell Cell;
public static boolean Data = false;
public static final int RowNum=3;
public static final int ColNum=1;
public static void main(String[] args) throws Exception{
SetData("D:\\Users\\wufangfang\\Desktop\\新建 Microsoft Excel 工作表.xlsx", "Sheet1");
}
public static void GetData(String Path,String SheetName){
}
public static void SetData(String Path,String SheetName) throws IOException{
//创建文件流
FileInputStream ExcelFile = new FileInputStream(Path);
ExcelBook = new XSSFWorkbook(ExcelFile);
//创建字体,设置其为红色、粗体
XSSFFont font = ExcelBook.createFont();
font.setColor(HSSFFont.COLOR_RED);
//设置单元格颜色
CellStyle style = ExcelBook.createCellStyle();
/*
* 调整颜色修改后面的 “15”
style.setFillForegroundColor((short) 15);// 设置背景色
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
*/
//调整颜色修改GREY_25_PERCENT
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
try {
ExcelSheet = ExcelBook.getSheet(SheetName);
Row=ExcelSheet.getRow(RowNum);
if(Row==null){
//创建行
Row = ExcelSheet.createRow(RowNum);
}
XSSFCell Cell = Row.getCell(ColNum);
if(Cell==null){
//创建列
Cell = Row.createCell(ColNum);
}
Cell.setCellValue("你好");
//Cell.setCellStyle(style); style.setFont(font);两个都要写 要不然设置的字体颜色和单元格颜色不能启用
//应用单元格设置
Cell.setCellStyle(style);
//应用字体设置
style.setFont(font);
FileOutputStream fileout =new FileOutputStream(Path);
//setvalues完后别忘了 write 调了一中午 我日的,原来没有write;;;;
ExcelBook.write(fileout);
fileout.flush();
fileout.close();
System.out.println("数据写入成功");
} catch (Exception e) {
System.out.println("数据写入有误"+e.getMessage());
}
}
}
哎,刚开始设置好没有进行应用,检查了半中午,要命。。。。。