package demo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Scanner;
/**
* @author JIANGLA
* @date 2022/10/2617:06
*/
public class Test {
public static void main(String[] args) {
try {
Workbook workbook = new HSSFWorkbook();
Sheet sheet1 = workbook.createSheet("sheet1");
FileOutputStream fileOutputStream = new FileOutputStream(new File("C:\\Users\\86182\\Desktop\\数据测试\\jiang.xls"));
//添加数据
//添加逻辑
workbook.write(fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
每行
Row row1 = sheet1.createRow(0);//第几行
row1.createCell(0).setCellValue("张三");//第一行第一列放入“张三”
创建文字,设置字体颜色
// 创建字体
Font font = workbook.createFont();
font.setColor(Font.COLOR_RED);
// 创建单元格格式CellStyle
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFont(font);
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中红色
Row row = sheet1.createRow(1);// 行
Cell cell1 = row.createCell(2);
cell1.setCellValue("张三");
cell1.setCellStyle(cellStyle);
其他颜色,不同写法
font.setColor(HSSFColor.GREEN.index);//绿色
font.setColor(HSSFColor.BLUE.index);//蓝色
垂直居中
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
合并单元格
CellRangeAddress region1 = new CellRangeAddress(1,5,0,0);
sheet1.addMergedRegion(region1);
设置单元格宽度
sheet1.setColumnWidth(0, 30 * 256);
设置单元格高度
row.setHeight((short) (50 * 20));
设置背景颜色
cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
cellStyle.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
参考:
(8条消息) 设置Excel单元格背景色(setFillForegroundColor)_王者成功之路的博客-CSDN博客_setfillforegroundcolor 自定义颜色