POI 写入 Excel 时设置样式的例子

本文通过实例代码介绍了如何使用Apache POI库在Java中创建Excel文件,并详细讲解了如何设置单元格的字体、颜色、边框等样式,帮助开发者实现自定义的Excel报告。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
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;

public class ExcelUtils {

	/**
	 * 
	 * @param filePath
	 *            Excel 文件路径
	 * @param titleRow
	 *            标题栏 行号,1=第一行
	 * @param startRow
	 *            从第几行开始读取数据,1=第一行
	 * @return 读取到的数据集
	 */
	public static List<String[]> readExcel2003(String filePath, int titleRow, int startRow) {
		List<String[]> list = null;
		try {
			// System.out.println( "> > > start read..." );
			List<String[]> list_read = new ArrayList<String[]>();
			File excel_file = new File(filePath);// 读取的文件路径
			FileInputStream input = new FileInputStream(excel_file); // 读取的文件路径
			HSSFWorkbook wb = new HSSFWorkbook(new BufferedInputStream(input));
			Sheet sheet = wb.getSheetAt(0); // 读取第一个 sheet

			int maxRowNumber = sheet.getPhysicalNumberOfRows();// 获取总行数,保留空行
			// System.out.println( "总行数(包括空行):"+maxRowNumber );
			// System.out.println( "标题行:"+startRow );
			// System.out.println( "开始行:"+startRow );
			int maxCellNumber = sheet.getRow(titleRow - 1).getPhysicalNumberOfCells(); // 获取总列数
			// System.out.println( "总列数:"+maxCellNumber );
			for (int r = startRow - 1; r < maxRowNumber; r++) {
				Row row = sheet.getRow(r);
				String[] cellObject = new String[maxCellNumber];
				for (int s = 0; s < maxCellNumber; s++) {
					Cell cell = row.getCell(s);
					if (cell != null) {
						// cellObject[s] = String.valueOf(cell);

						// 把数字当成String来读,避免出现1读成1.0的情况
						if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
							cell.setCellType(Cell.CELL_TYPE_STRING);
						}
						// 判断数据的类型
						switch (cell.getCellType()) {
						case Cell.CELL_TYPE_NUMERIC: // 数字
							cellObject[s] = String.valueOf(cell.getNumericCellValue());
							break;
						case Cell.CELL_TYPE_STRING: // 字符串
							cellObject[s] = String.valueOf(cell.getStringCellValue());
							break;
						case Cell.CELL_TYPE_BOOLEAN: // Boolean
							cellObject[s] = String.valueOf(cell.getBooleanCellValue());
							break;
						case Cell.CELL_TYPE_FORMULA: // 公式
							cellObject[s] = String.valueOf(cell.getCellFormula());
							break;
						case Cell.CELL_TYPE_BLANK: // 空值
							cellObject[s] = "";
							break;
						case Cell.CELL_TYPE_ERROR: // 故障
							cellObject[s] = null;
							break;
						default:
							cellObject[s] = null;
							break;
						}

					}
				}
				if (null != cellObject) {
					if (null != cellObject[1]) { // 第2列 [证券代码] 不能为空
						list_read.add(cellObject);
					}
				}

			}

			list = list_read;
			// System.out.println( "> > > 有效记录数(除去空行和标题栏) :"+ list.size() );
			// wb.unLock();
			wb.close();
			input.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 写入 REG 文件
	 * 
	 * @param filePath
	 *            生成的文件路径
	 * @param list
	 *            数据集
	 * @return
	 */
	public static boolean writeExcel2003(String filePath, List<String[]> list) {
		boolean bl = false;
		try {

			Workbook wb = new HSSFWorkbook();
			// Workbook wb = new XSSFWorkbook();
			CreationHelper createHelper = wb.getCreationHelper();
			Sheet sheet = wb.createSheet("REG-Report-" + DateUtils.getNowDateTime("yyyyMMdd"));
			// 设置全局单元格宽度,"2012-08-10"的宽度为2500,英文或数字或英文符号 宽度为250?
			sheet.setColumnWidth(1, 5000); 
			sheet.setColumnWidth(2, 5000);
			sheet.setColumnWidth(3, 5000);
			sheet.setColumnWidth(4, 5000);
			sheet.setColumnWidth(5, 5000);
			sheet.setColumnWidth(6, 5000);
			sheet.setColumnWidth(7, 5000);
			sheet.setColumnWidth(8, 5000);
			sheet.setColumnWidth(9, 6000);

			// 整个sheet的 默认样式 
			Font font_default = wb.createFont(); 
			font_default.setFontName("Courier New");// 默认 字体名称
			font_default.setFontHeightInPoints((short) 14); // 默认 字体大小
			font_default.setColor(HSSFColor.BLACK.index);// 默认 字体黑色
			CellStyle style_default = wb.createCellStyle();
			style_default.setFillForegroundColor( HSSFColor.WHITE.index ); //白色背景
			style_default.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  //白色背景
			style_default.setFont(font_default);
			style_default.setBorderBottom((short) 0); // 边框 宽度
			style_default.setBorderLeft((short) 0);
			style_default.setBorderRight((short) 0);
			style_default.setBorderTop((short) 0);
			style_default.setBottomBorderColor(HSSFColor.WHITE.index); // 边框 颜色
			style_default.setLeftBorderColor(HSSFColor.WHITE.index);
			style_default.setRightBorderColor(HSSFColor.WHITE.index);
			style_default.setTopBorderColor(HSSFColor.WHITE.index);

			// 报表数据的 默认样式
			Font font_data = wb.createFont(); 
			font_data.setFontName("Courier New");
			font_data.setColor(HSSFColor.BLACK.index);
			CellStyle style_data = wb.createCellStyle();
			style_data.setFont(font_data);
			style_data.setAlignment(HSSFCellStyle.ALIGN_LEFT); // 文本居中
			style_data.setBorderBottom((short) 1);
			style_data.setBorderLeft((short) 1);
			style_data.setBorderRight((short) 1);
			style_data.setBorderTop((short) 1);
			style_data.setBottomBorderColor(HSSFColor.GREY_80_PERCENT.index);
			style_data.setLeftBorderColor(HSSFColor.GREY_80_PERCENT.index);
			style_data.setRightBorderColor(HSSFColor.GREY_80_PERCENT.index);
			style_data.setTopBorderColor(HSSFColor.GREY_80_PERCENT.index);			
			
			
			// 报表 抬头 样式 :Hundsun REG ,字号:24,加粗,字体颜色:黑色,字体:Times New Roman,背景颜色:白色
			Font font0 = wb.createFont(); 
			font0.setFontName("Times New Roman"); //字体
			font0.setBold(true); // 加粗
			font0.setColor(HSSFColor.BLACK.index);// 黑色
			font0.setFontHeightInPoints((short) 24); //字体大小
			CellStyle style0 = wb.createCellStyle();
			style0.setFillForegroundColor( HSSFColor.WHITE.index ); //白色背景
			style0.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			style0.setFont(font0);
			style0.setBorderBottom((short) 0);
			style0.setBorderLeft((short) 0);
			style0.setBorderRight((short) 0);
			style0.setBorderTop((short) 0);
			style0.setBottomBorderColor(HSSFColor.WHITE.index);
			style0.setLeftBorderColor(HSSFColor.WHITE.index);
			style0.setRightBorderColor(HSSFColor.WHITE.index);
			style0.setTopBorderColor(HSSFColor.WHITE.index);			
			// 写入 抬头
			Row row0 = sheet.createRow(0); //第 1 行
			row0.setRowStyle( style_default );
			Cell cell00 = row0.createCell(0);
			cell00.setCellValue(createHelper.createRichTextString("Hundsun REG"));
			cell00.setCellStyle( style0 ); // 覆盖 默认样式
			Row row1 = sheet.createRow(1); //第 2 行
			row1.setRowStyle( style_default );
			Row row2 = sheet.createRow(2); //第 3 行
			row2.setRowStyle( style_default );
			
			// 报表 表头 样式
			Font font3 = wb.createFont(); 
			font3.setFontName("Courier New");
			font3.setBold(true);
			font3.setColor(HSSFColor.WHITE.index);
			CellStyle style3 = wb.createCellStyle();
			style3.setFont(font3);
			style3.setFillForegroundColor(HSSFColor.RED.index); // 背景颜色
			style3.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); // 背景填充方式,此语句必须要设置,不然背景色无效
			style3.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 文本居中
			style3.setBorderBottom((short) 1);
			style3.setBorderLeft((short) 1);
			style3.setBorderRight((short) 1);
			style3.setBorderTop((short) 1);
			style3.setBottomBorderColor(HSSFColor.GREY_80_PERCENT.index);
			style3.setLeftBorderColor(HSSFColor.GREY_80_PERCENT.index);
			style3.setRightBorderColor(HSSFColor.GREY_80_PERCENT.index);
			style3.setTopBorderColor(HSSFColor.GREY_80_PERCENT.index);			
			// 写入 表头
			Row row3 = sheet.createRow(3); // 第4行
			row3.setRowStyle( style_default );
			Cell cell30 = row3.createCell(0);
			cell30.setCellValue(createHelper.createRichTextString("AA*"));
			cell30.setCellStyle(style3);
			Cell cell31 = row3.createCell(1);
			cell31.setCellValue(createHelper.createRichTextString("BB"));
			cell31.setCellStyle(style3);
			Cell cell32 = row3.createCell(2);
			cell32.setCellValue(createHelper.createRichTextString("CC"));
			cell32.setCellStyle(style3);
			Cell cell33 = row3.createCell(3);
			cell33.setCellValue(createHelper.createRichTextString("DD"));
			cell33.setCellStyle(style3);
			Cell cell34 = row3.createCell(4);
			cell34.setCellValue(createHelper.createRichTextString("EE"));
			cell34.setCellStyle(style3);
			Cell cell35 = row3.createCell(5);
			cell35.setCellValue(createHelper.createRichTextString("FF"));
			cell35.setCellStyle(style3);
			Cell cell36 = row3.createCell(6);
			cell36.setCellValue(createHelper.createRichTextString("GG"));
			cell36.setCellStyle(style3);
			Cell cell37 = row3.createCell(7);
			cell37.setCellValue(createHelper.createRichTextString("HH"));
			cell37.setCellStyle(style3);
			Cell cell38 = row3.createCell(8);
			cell38.setCellValue(createHelper.createRichTextString("II"));
			cell38.setCellStyle(style3);
			Cell cell39 = row3.createCell(9);
			cell39.setCellValue(createHelper.createRichTextString("JJ"));
			cell39.setCellStyle(style3);

			Row rowx;			
			if (null != list && list.size() > 0) {
				for (int x = 0; x < list.size(); x++) {					
					rowx = sheet.createRow(x + 4); // 第 5 行 开始
					rowx.setRowStyle(style_default);
					Cell cellx0 = rowx.createCell(0);
					cellx0.setCellValue(createHelper.createRichTextString(list.get(x)[0]));
					cellx0.setCellStyle( style_data );
					Cell cellx1 = rowx.createCell(1);
					cellx1.setCellValue(createHelper.createRichTextString(list.get(x)[1]));
					cellx1.setCellStyle( style_data );
					Cell cellx2 = rowx.createCell(2);
					cellx2.setCellValue(createHelper.createRichTextString(list.get(x)[2]));
					cellx2.setCellStyle( style_data );
					Cell cellx3 = rowx.createCell(3);
					cellx3.setCellValue(createHelper.createRichTextString(list.get(x)[3]));
					cellx3.setCellStyle( style_data );
					Cell cellx4 = rowx.createCell(4);
					cellx4.setCellValue(createHelper.createRichTextString(list.get(x)[4]));
					cellx4.setCellStyle( style_data );
					Cell cellx5 = rowx.createCell(5);
					cellx5.setCellValue(createHelper.createRichTextString(list.get(x)[5]));
					cellx5.setCellStyle( style_data );
					Cell cellx6 = rowx.createCell(6);
					cellx6.setCellValue(createHelper.createRichTextString(list.get(x)[6]));
					cellx6.setCellStyle( style_data );
					Cell cellx7 = rowx.createCell(7);
					cellx7.setCellValue(createHelper.createRichTextString(list.get(x)[7]));
					cellx7.setCellStyle( style_data );
					Cell cellx8 = rowx.createCell(8);
					cellx8.setCellValue(createHelper.createRichTextString(list.get(x)[8]));
					cellx8.setCellStyle( style_data );
					Cell cellx9 = rowx.createCell(9);
					cellx9.setCellValue(createHelper.createRichTextString(list.get(x)[9]));
					cellx9.setCellStyle( style_data );
				}

			}
			
			// 增加写入一些空白的行,达到视觉效果上看起来全部都是白色背景
			Row row_end;	
			for (int x9 = 0; x9 < 50 ; x9++) {					
				row_end = sheet.createRow( (list.size()+4) + x9 ); 
				row_end.setRowStyle(style_default);
			}
			OutputStream fileOut = new FileOutputStream(filePath);
			wb.write(fileOut);
			fileOut.close();
			wb.close();
			bl = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bl;
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值