excle-poi

excle常用
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
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.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TestExclePoi {

	public static void main(String[] args) throws IOException {
		
		//测试poi
		Workbook wb_xls = null;
		Workbook wb_xlsx = null;
		
		wb_xls = new HSSFWorkbook();//03版
		wb_xlsx = new XSSFWorkbook();//07版
		
		//基本操作:
		
		//创建表单
		Sheet sheet = wb_xls.createSheet();
		//表单创建行
		Row row = sheet.createRow(0);//创建第一行,从0开始
		//行创建列
		Cell cell = row.createCell(0);
		//写入数据
		cell.setCellValue("单元格写入数据");
		
		//*********************************************************************************
		//设置单元格样式
		
		//1.创建样式对象
		CellStyle style = wb_xls.createCellStyle();
		//2.设置样式
		
			//水平居中
			style.setAlignment(CellStyle.ALIGN_CENTER);//水准居中
			style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);//垂直居中,两个需要一起设置
		
			//边框细线
			style.setBorderTop(CellStyle.BORDER_THIN);
			style.setBorderBottom(CellStyle.BORDER_THIN);
			style.setBorderLeft(CellStyle.BORDER_THIN);
			style.setBorderRight(CellStyle.BORDER_THIN);
		
			//设置背景颜色
			style.setFillBackgroundColor(IndexedColors.BLACK.index);//背景色,默认也是黑
			style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.index);//前景色,单元格的颜色
			style.setFillPattern(CellStyle.SOLID_FOREGROUND);//缺失不显示颜色,设置样式//https://blog.csdn.net/u014677702/article/details/84573271
		
		
			//设置字体格式
			Font font = wb_xls.createFont();
			
			font.setFontName("黑体");//字体
			font.setFontHeightInPoints((short) 10);//行高
			font.setBoldweight((short) 4);//粗体
			font.setColor(IndexedColors.RED.index);//字体颜色
		
			style.setFont(font);
			
		//3.保存到单元格中
		cell.setCellStyle(style);
		
		//表单设置列宽
		sheet.setColumnWidth(0, 20*256);//设置第0宽度约为20,必须乘256
		
		//合并单元格:sheet
		int firstRow = 0;
		int lastRow = 3;
		int firstCol = 0;
		int lastCol = 4;
		sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol));
		
		//****************************************************************************************
		//生成资源
		
		//创建文件
		File file = new File("D:/Tedu_wkspace/excle/teatCreate.xls");
		//创建输出流,输出数据
		OutputStream stream = new FileOutputStream(file);
		//吧wb对象写到输出流中
		wb_xls.write(stream);
		//写出数据
		stream.flush();
		//关闭资源
		stream.close();
	}
}


代码效果:
代码效果

猜你喜欢

转载自blog.csdn.net/weixin_42763300/article/details/89219379
今日推荐