java 基于 POI 导出 excel文件

生成 excel 的方法有两种。第一种,就像修房子一样,一块砖一块瓦,一点点修葺起来; 第二种,先导入个模版,再将自己要显示的数据放在 需要显示 的地方,然后生成excel. 两种方法各有利弊,相信对大家而言是不言而喻的,使用时自己做权衡取舍。

第一种,原生态 法:(PoiCreateExcel.java)

<span style="font-size:18px;">package com.conserv.tsas.test;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFHyperlink;
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;
import org.apache.poi.ss.util.CellRangeAddress;

/**
 * @author Administrator
 * 无模版 生成 excel 
 */
public class PoiCreateExcel {
	public static void main(String[] args) throws Exception {
		
		// 创建 Excel 的工作书册 Workbook, 对应到一个 excel 文档
		HSSFWorkbook wb = new HSSFWorkbook();
		
		// 创建 Excel 的工作 sheet, 对应到一个excel文档的tab
		HSSFSheet sheet = wb.createSheet("sheet_1");
		
		// 设置 excel 每列的宽度
		sheet.setColumnWidth(0, 4000);
		sheet.setColumnWidth(1, 4000);
		//sheet.setColumnWidth(1, 8000);
		
		// 创建字体样式
		HSSFFont font = wb.createFont();
		font.setFontName("宋体");
		font.setBoldweight((short) 100);
		font.setFontHeight((short) 300);
		font.setColor(HSSFColor.BLUE.index);
		
		// 创建单元格样式
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		style.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
		
		// 设置边框
		style.setBottomBorderColor(HSSFColor.RED.index);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		
		// 设置字体
		style.setFont(font);
		
		// 创建  excel 的 sheet 的一行
		HSSFRow row = sheet.createRow(0);
		row.setHeight((short) 500); // 设置行高
		// 创建一个 excel 的单元格
		HSSFCell cell = row.createCell(0);
		HSSFCell cell2 = row.createCell(1);
		cell2.setCellStyle(style);
		
		// 合并单元格
		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 1));
		
		// 给 excel  设置样式 和赋值
		cell.setCellStyle(style);
		cell.setCellValue(" hell word ");
		
		// 设置单元格 内容格式
		HSSFCellStyle style1 = wb.createCellStyle();
		style1.setDataFormat(HSSFDataFormat.getBuiltinFormat("h:mm:ss"));
		style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		// 自动换行
		style1.setWrapText(true);
		
		style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		//style1.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style1.setBorderRight(HSSFCellStyle.BORDER_THIN); 
		
		row = sheet.createRow(1);
		row.setHeight((short) 500);
		
		// 设置单元格样式
		cell = row.createCell(0);
		cell.setCellStyle(style1);
		cell.setCellValue(new Date());
		
		HSSFCellStyle style2 = wb.createCellStyle();
		style2.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
		style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		
		style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		//style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style2.setBorderRight(HSSFCellStyle.BORDER_THIN); 
		
		// 创建超级链接
		HSSFHyperlink link = new HSSFHyperlink(HSSFHyperlink.LINK_URL);
		link.setAddress("http://www.baidu.com");
		cell = row.createCell(1);
		cell.setCellValue("百度");
		// 设置单元格链接
		cell.setHyperlink(link);
		cell.setCellStyle(style2);
		
		FileOutputStream fos = new FileOutputStream(new File("d:/workbook.xls"));
		wb.write(fos);
		fos.close();
		
		System.out.println("success!");
	}
}

最终效果:




第二种,模版 法:

package com.conserv.tsas.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
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;

public class PoiTestExcel {
	public static void main(String[] args) {
		try {
			File file = new File("d:/model.xls");
			// InputStream is = new FileInputStream("");
			POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
			Workbook work = new HSSFWorkbook(fs);

			// 得到 excel 的第 0 张表
			Sheet sheet = work.getSheetAt(0);

			// 得到第 三 行的第一个单元格的样式
			Row rowcellStyle = sheet.getRow(2);
			CellStyle column1 = rowcellStyle.getCell(0).getCellStyle();

			// 这里的行和列的数法与计算机里的一样,从 0 开始计数
			// 填充 title 数据
			Row row = sheet.getRow(0);
			Cell cell = row.getCell(0);
			cell.setCellValue("复旦大学    2010年花样名册");
			int number = 0, i = 0;
			// 得到行,并填充数据和表格样式
			for (i = 2; i < 12; i++) {
				//row = sheet.getRow(i); // 得到行
				row = sheet.createRow(i);
				row.setHeight((short) 400);
				
				cell = row.createCell(0);	// 得到第 0 个单元格
				cell.setCellValue("貂蝉 " + (i-1));
				cell.setCellStyle(column1); // 填充样式

				cell = row.createCell(1);
				cell.setCellValue("女");
				cell.setCellStyle(column1);// 填充样式

				cell = row.createCell(2);
				Date date = new Date();
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				cell.setCellValue(df.format(date));
				cell.setCellStyle(column1);// 填充样式

				cell = row.createCell(3);
				cell.setCellValue("15901215678");
				cell.setCellStyle(column1);// 填充样式

				cell = row.createCell(4);
				cell.setCellValue("上海市浦东世纪大道");
				cell.setCellStyle(column1);// 填充样式

				cell = row.createCell(5);
				cell.setCellValue("无");
				cell.setCellStyle(column1);// 填充样式
				// .....给每个单元格填充数据和样式

				number++;
			}

			// 最后一行, 创建每个单元格,添加样式,然后合并
			row = sheet.createRow(i);
			row.setHeight((short) 500);
			cell = row.createCell(0);
			cell.setCellValue("总计:" + number + "个学生"); // 填充值
			cell.setCellStyle(column1);

			cell = row.createCell(1);
			cell.setCellStyle(column1);

			cell = row.createCell(2);
			cell.setCellStyle(column1);

			cell = row.createCell(3);
			cell.setCellStyle(column1);

			cell = row.createCell(4);
			cell.setCellStyle(column1);

			cell = row.createCell(5);
			cell.setCellStyle(column1);

			// 合并单元格
			sheet.addMergedRegion(new CellRangeAddress(i, i, 0, 5));
			FileOutputStream fos = new FileOutputStream("d:/workbook_2.xls");
			work.write(fos);
			fos.close();

			System.out.println("恭喜你,  操作成功!");
		} catch (FileNotFoundException e) {
			System.out.println("文件路径错误!");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("文件输入流错误!");
			e.printStackTrace();
		}

	}
}
导入的模版:



操作成功后的 excel 效果:



呵呵, 是不是又快又漂亮呢??? 

如果,本文对你有用,亲,记得好评哟!!!



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个完整的 Java POI 导出 Excel 文件并下载的示例代码: ```java import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelExportUtil { public static void export(HttpServletResponse response) throws IOException { // 创建工作簿 Workbook workbook = new XSSFWorkbook(); // 创建工作表 Sheet sheet = workbook.createSheet("Sheet1"); // 添加表头行 Row headerRow = sheet.createRow(0); Cell headerCell1 = headerRow.createCell(0); headerCell1.setCellValue("Name"); Cell headerCell2 = headerRow.createCell(1); headerCell2.setCellValue("Age"); // 添加数据行 List<Person> personList = getPersonList(); for (int i = 0; i < personList.size(); i++) { Person person = personList.get(i); Row row = sheet.createRow(i + 1); Cell cell1 = row.createCell(0); cell1.setCellValue(person.getName()); Cell cell2 = row.createCell(1); cell2.setCellValue(person.getAge()); } // 设置响应头,告诉浏览器下载文件 response.setHeader("Content-Disposition", "attachment;filename=example.xlsx"); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // 将工作簿写入响应输出流 workbook.write(response.getOutputStream()); // 关闭工作簿 workbook.close(); } private static List<Person> getPersonList() { List<Person> personList = new ArrayList<>(); personList.add(new Person("Alice", 20)); personList.add(new Person("Bob", 25)); personList.add(new Person("Charlie", 30)); return personList; } private static class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } } ``` 这段代码定义了一个名为 `ExcelExportUtil` 的类,其中包含了一个名为 `export` 的静态方法,用于导出 Excel 文件并下载。在 `export` 方法中,首先创建了一个工作簿对象 `workbook`,然后创建了一个工作表对象 `sheet`,并向其中添加了表头行和数据行。最后将工作簿写入响应输出流,并设置响应头,告诉浏览器下载文件。 在 `getPersonList` 方法中,定义了一个名为 `Person` 的内部类,用于存储人员信息。在示例代码中,生成了一个包含三个人员信息的列表。 如果需要调用上述代码,可以在 Servlet 或者 Spring MVC 的控制器中使用以下代码: ```java @RequestMapping("/download") public void download(HttpServletResponse response) throws IOException { ExcelExportUtil.export(response); } ``` 其中 `"/download"` 是一个映射到下载方法的 URL。这段代码会调用 `ExcelExportUtil` 类的静态方法 `export`,并将响应对象 `response` 传递给它。需要注意的是,需要将 `HttpServletResponse` 对象作为参数传递给 `export` 方法,以便将 Excel 文件写入响应输出流。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值