JavaDemo——POI写Excel

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/FlyLikeButterfly/article/details/80528682

maven添加:

	<dependency>
	    <groupId>org.apache.poi</groupId>
	    <artifactId>poi</artifactId>
	    <version>3.17</version>
	</dependency>

测试Demo:

/**
 * createtime : 2018年3月8日 下午4:06:33
 */
package candel.javatest;


import java.io.FileOutputStream;
import java.io.IOException;


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.hssf.util.HSSFColor.HSSFColorPredefined;
import org.apache.poi.ss.usermodel.FillPatternType;


/**
 * TODO
 * @author XWF
 */
public class POItest {


	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("helloworld");//Sheet名称
		for(int i=0;i<10;i++) {
			HSSFRow row = sheet.createRow(i);//行
			for(int j=0;j<10;j++) {
				HSSFCell cell = row.createCell(j);//单元格
				String val = createString(i,j);
				setCellStyle(i,j,cell,wb);//设置样式
				cell.setCellValue(val);//设置值
			}
		}
		
		FileOutputStream fos = new FileOutputStream("E:\\Temp\\exceltest.xls");//写入文件
		wb.write(fos);
		fos.flush();
		fos.close();
		System.out.println("xls finished.");
	}


	private static void setCellStyle(int i, int j, HSSFCell cell,HSSFWorkbook wb) {
		HSSFFont font1 = wb.createFont();
		HSSFCellStyle style1 = wb.createCellStyle();
		font1.setColor(HSSFColorPredefined.BLUE.getIndex());//字体格式
		font1.setBold(true);
		style1.setFillPattern(FillPatternType.SOLID_FOREGROUND);//单元格格式
		style1.setFillForegroundColor(HSSFColorPredefined.LIGHT_YELLOW.getIndex());
		style1.setFont(font1);
		HSSFFont font2 = wb.createFont();
		HSSFCellStyle style2 = wb.createCellStyle();
		font2.setColor(HSSFColorPredefined.GREY_80_PERCENT.getIndex());
		style2.setFont(font2);
		if(0==i && 0==j) {
			cell.setCellStyle(style1);
		}else if(0==i) {
			cell.setCellStyle(style1);
		}else if(0==j){
			cell.setCellStyle(style1);
		}else if(j>i){
		}else {
			cell.setCellStyle(style2);
		}
	}


	private static String createString(int i, int j) {
		if(0==i && 0==j) {
			return "九九乘法";
		}else if(0==i) {
			return j+"";
		}else if(0==j){
			return i+"";
		}else if(j>i){
			return "";
		}else {
			return j+"*"+i+"="+(i*j);
		}
	}


}

生成的Excel:


猜你喜欢

转载自blog.csdn.net/FlyLikeButterfly/article/details/80528682
今日推荐