java导出Excel通用方法实例

数据导出到Excel几乎是所有客户都会提出的一个需求。下面我就分享一下我的代码。

首先需要引入的jar包:

然后就是正式代码了。

以上包不知道怎么引,直接去代码中借助idea可以直接引入

package lcy._41_50;
 
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
 
import javax.servlet.http.HttpServletResponse;
 
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.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
 
@SuppressWarnings( { "deprecation" })
public class Test46 {
 
	public static void main(String[] args) throws Exception {
 
		String sheetName = "用车统计表单";
		String titleName = "用车申请数据统计表";
		String fileName = "用车申请统计表单";
		int columnNumber = 3;
		int[] columnWidth = { 10, 20, 30 };
		String[][] dataList = { { "001", "2015-01-01", "IT" },
				{ "002", "2015-01-02", "市场部" }, { "003", "2015-01-03", "测试" } };
		String[] columnName = { "单号", "申请时间", "申请部门" };
		new Test46().ExportNoResponse(sheetName, titleName, fileName,
				columnNumber, columnWidth, columnName, dataList);
	}
 
	public void ExportWithResponse(String sheetName, String titleName,
			String fileName, int columnNumber, int[] columnWidth,
			String[] columnName, String[][] dataList,
			HttpServletResponse response) throws Exception {
		if (columnNumber == columnWidth.length&& columnWidth.length == columnName.length) {
			// 第一步,创建一个webbook,对应一个Excel文件
			HSSFWorkbook wb = new HSSFWorkbook();
			// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
			HSSFSheet sheet = wb.createSheet(sheetName);
			// sheet.setDefaultColumnWidth(15); //统一设置列宽
			for (int i = 0; i < columnNumber; i++) 
			{
				for (int j = 0; j <= i; j++) 
				{
					if (i == j) 
					{
						sheet.setColumnWidth(i, columnWidth[j] * 256); // 单独设置每列的宽
					}
				}
			}
			// 创建第0行 也就是标题
			HSSFRow row1 = sheet.createRow((int) 0);
			row1.setHeightInPoints(50);// 设备标题的高度
			// 第三步创建标题的单元格样式style2以及字体样式headerFont1
			HSSFCellStyle style2 = wb.createCellStyle();
			style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
			style2.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);
			style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			HSSFFont headerFont1 = (HSSFFont) wb.createFont(); // 创建字体样式
			headerFont1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
			headerFont1.setFontName("黑体"); // 设置字体类型
			headerFont1.setFontHeightInPoints((short) 15); // 设置字体大小
			style2.setFont(headerFont1); // 为标题样式设置字体样式
 
			HSSFCell cell1 = row1.createCell(0);// 创建标题第一列
			sheet.addMergedRegion(new CellRangeAddress(0, 0, 0,
					columnNumber - 1)); // 合并列标题
			cell1.setCellValue(titleName); // 设置值标题
			cell1.setCellStyle(style2); // 设置标题样式
 
			// 创建第1行 也就是表头
			HSSFRow row = sheet.createRow((int) 1);
			row.setHeightInPoints(37);// 设置表头高度
 
			// 第四步,创建表头单元格样式 以及表头的字体样式
			HSSFCellStyle style = wb.createCellStyle();
			style.setWrapText(true);// 设置自动换行
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个居中格式
 
			style.setBottomBorderColor(HSSFColor.BLACK.index);
			style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
			style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
			style.setBorderRight(HSSFCellStyle.BORDER_THIN);
			style.setBorderTop(HSSFCellStyle.BORDER_THIN);
 
			HSSFFont headerFont = (HSSFFont) wb.createFont(); // 创建字体样式
			headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
			headerFont.setFontName("黑体"); // 设置字体类型
			headerFont.setFontHeightInPoints((short) 10); // 设置字体大小
			style.setFont(headerFont); // 为标题样式设置字体样式
 
			// 第四.一步,创建表头的列
			for (int i = 0; i < columnNumber; i++) 
			{
				HSSFCell cell = row.createCell(i);
				cell.setCellValue(columnName[i]);
				cell.setCellStyle(style);
			}
 
			// 第五步,创建单元格,并设置值
			for (int i = 0; i < dataList.length; i++) 
			{
				row = sheet.createRow((int) i + 2);
				// 为数据内容设置特点新单元格样式1 自动换行 上下居中
				HSSFCellStyle zidonghuanhang = wb.createCellStyle();
				zidonghuanhang.setWrapText(true);// 设置自动换行
				zidonghuanhang.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个居中格式
 
				// 设置边框
				zidonghuanhang.setBottomBorderColor(HSSFColor.BLACK.index);
				zidonghuanhang.setBorderBottom(HSSFCellStyle.BORDER_THIN);
				zidonghuanhang.setBorderLeft(HSSFCellStyle.BORDER_THIN);
				zidonghuanhang.setBorderRight(HSSFCellStyle.BORDER_THIN);
				zidonghuanhang.setBorderTop(HSSFCellStyle.BORDER_THIN);
 
				// 为数据内容设置特点新单元格样式2 自动换行 上下居中左右也居中
				HSSFCellStyle zidonghuanhang2 = wb.createCellStyle();
				zidonghuanhang2.setWrapText(true);// 设置自动换行
				zidonghuanhang2
						.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个上下居中格式
				zidonghuanhang2.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
 
				// 设置边框
				zidonghuanhang2.setBottomBorderColor(HSSFColor.BLACK.index);
				zidonghuanhang2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
				zidonghuanhang2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
				zidonghuanhang2.setBorderRight(HSSFCellStyle.BORDER_THIN);
				zidonghuanhang2.setBorderTop(HSSFCellStyle.BORDER_THIN);
				HSSFCell datacell = null;
				for (int j = 0; j < columnNumber; j++) 
				{
					datacell = row.createCell(j);
					datacell.setCellValue(dataList[i][j]);
					datacell.setCellStyle(zidonghuanhang2);
				}
			}
 
			// 第六步,将文件存到浏览器设置的下载位置
			String filename = fileName + ".xls";
			response.setContentType("application/ms-excel;charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename="
					.concat(String.valueOf(URLEncoder.encode(filename, "UTF-8"))));
			OutputStream out = response.getOutputStream();
			try {
				wb.write(out);// 将数据写出去
				String str = "导出" + fileName + "成功!";
				System.out.println(str);
			} catch (Exception e) {
				e.printStackTrace();
				String str1 = "导出" + fileName + "失败!";
				System.out.println(str1);
			} finally {
				out.close();
			}
 
		} else {
			System.out.println("列数目长度名称三个数组长度要一致");
		}
 
	}
 
	public void ExportNoResponse(String sheetName, String titleName,
			String fileName, int columnNumber, int[] columnWidth,
			String[] columnName, String[][] dataList) throws Exception {
		if (columnNumber == columnWidth.length&& columnWidth.length == columnName.length) {
			// 第一步,创建一个webbook,对应一个Excel文件
			HSSFWorkbook wb = new HSSFWorkbook();
			// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
			HSSFSheet sheet = wb.createSheet(sheetName);
			// sheet.setDefaultColumnWidth(15); //统一设置列宽
			for (int i = 0; i < columnNumber; i++) 
			{
				for (int j = 0; j <= i; j++) 
				{
					if (i == j) 
					{
						sheet.setColumnWidth(i, columnWidth[j] * 256); // 单独设置每列的宽
					}
				}
			}
			// 创建第0行 也就是标题
			HSSFRow row1 = sheet.createRow((int) 0);
			row1.setHeightInPoints(50);// 设备标题的高度
			// 第三步创建标题的单元格样式style2以及字体样式headerFont1
			HSSFCellStyle style2 = wb.createCellStyle();
			style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
			style2.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);
			style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			HSSFFont headerFont1 = (HSSFFont) wb.createFont(); // 创建字体样式
			headerFont1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
			headerFont1.setFontName("黑体"); // 设置字体类型
			headerFont1.setFontHeightInPoints((short) 15); // 设置字体大小
			style2.setFont(headerFont1); // 为标题样式设置字体样式
 
			HSSFCell cell1 = row1.createCell(0);// 创建标题第一列
			sheet.addMergedRegion(new CellRangeAddress(0, 0, 0,
					columnNumber - 1)); // 合并第0到第17列
			cell1.setCellValue(titleName); // 设置值标题
			cell1.setCellStyle(style2); // 设置标题样式
 
			// 创建第1行 也就是表头
			HSSFRow row = sheet.createRow((int) 1);
			row.setHeightInPoints(37);// 设置表头高度
 
			// 第四步,创建表头单元格样式 以及表头的字体样式
			HSSFCellStyle style = wb.createCellStyle();
			style.setWrapText(true);// 设置自动换行
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个居中格式
 
			style.setBottomBorderColor(HSSFColor.BLACK.index);
			style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
			style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
			style.setBorderRight(HSSFCellStyle.BORDER_THIN);
			style.setBorderTop(HSSFCellStyle.BORDER_THIN);
 
			HSSFFont headerFont = (HSSFFont) wb.createFont(); // 创建字体样式
			headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
			headerFont.setFontName("黑体"); // 设置字体类型
			headerFont.setFontHeightInPoints((short) 10); // 设置字体大小
			style.setFont(headerFont); // 为标题样式设置字体样式
 
			// 第四.一步,创建表头的列
			for (int i = 0; i < columnNumber; i++) 
			{
				HSSFCell cell = row.createCell(i);
				cell.setCellValue(columnName[i]);
				cell.setCellStyle(style);
			}
 
			// 第五步,创建单元格,并设置值
			for (int i = 0; i < dataList.length; i++) 
			{
				row = sheet.createRow((int) i + 2);
				// 为数据内容设置特点新单元格样式1 自动换行 上下居中
				HSSFCellStyle zidonghuanhang = wb.createCellStyle();
				zidonghuanhang.setWrapText(true);// 设置自动换行
				zidonghuanhang
						.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个居中格式
 
				// 设置边框
				zidonghuanhang.setBottomBorderColor(HSSFColor.BLACK.index);
				zidonghuanhang.setBorderBottom(HSSFCellStyle.BORDER_THIN);
				zidonghuanhang.setBorderLeft(HSSFCellStyle.BORDER_THIN);
				zidonghuanhang.setBorderRight(HSSFCellStyle.BORDER_THIN);
				zidonghuanhang.setBorderTop(HSSFCellStyle.BORDER_THIN);
 
				// 为数据内容设置特点新单元格样式2 自动换行 上下居中左右也居中
				HSSFCellStyle zidonghuanhang2 = wb.createCellStyle();
				zidonghuanhang2.setWrapText(true);// 设置自动换行
				zidonghuanhang2
						.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个上下居中格式
				zidonghuanhang2.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
 
				// 设置边框
				zidonghuanhang2.setBottomBorderColor(HSSFColor.BLACK.index);
				zidonghuanhang2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
				zidonghuanhang2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
				zidonghuanhang2.setBorderRight(HSSFCellStyle.BORDER_THIN);
				zidonghuanhang2.setBorderTop(HSSFCellStyle.BORDER_THIN);
				HSSFCell datacell = null;
				for (int j = 0; j < columnNumber; j++) 
				{
					datacell = row.createCell(j);
					datacell.setCellValue(dataList[i][j]);
					datacell.setCellStyle(zidonghuanhang2);
				}
			}
 
			// 第六步,将文件存到指定位置
			try {
				FileOutputStream fout = new FileOutputStream("D:students.xls");
				wb.write(fout);
				String str = "导出" + fileName + "成功!";
				System.out.println(str);
				fout.close();
			} catch (Exception e) {
				e.printStackTrace();
				String str1 = "导出" + fileName + "失败!";
				System.out.println(str1);
			}
		} else {
			System.out.println("列数目长度名称三个数组长度要一致");
		}
 
	}
 
}

为了本地测试效果,单独写了一个无response参数的ExportNoResponse方法,直接将文件保存到指定目录D盘。

两个方法的不同就在于第六步中,有response参数的方法可以将文件存到浏览器设置的下载位置。

下面是导出效果截图:

以上所述是小编给大家介绍的java导出Excel方法详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java作为一种高级编程语言,具有强大的数据操作能力。在实际的开发过程中,我们经常需要将数据导出Excel表格中,以方便用户进行查看和操作。下面介绍Java导出Excel的三种方法方法一:POI框架 POI是Java中操作Excel的重要框架,它能够快速的读写Excel文档,各种类型的Excel文档都可以存取,使Excel文档操作更加简单方便。 使用POI框架,我们需要进行以下步骤: 1. 使用POI API创建工作簿、工作表等Excel对象。 2. 向工作表中创建行、单元格对象,设置数据。 3. 将数据写入Excel文件,保存Excel文件。 方法二:EasyExcel EasyExcel是一款简洁、易用、高效的Java操作Excel工具,它能够快速的读写Excel文档,支持大量数据写入,速度很快。 使用EasyExcel,我们需要进行以下步骤: 1. 使用EasyExcel API创建工作簿、工作表等Excel对象。 2. 向工作表中创建行、单元格对象,设置数据。 3. 将数据写入Excel文件,保存Excel文件。 方法三:Apache POI+Freemarker Apache POI+Freemarker是一种结合使用的方法,可以更加灵活、简便地操作Excel。 使用Apache POI+Freemarker,我们需要进行以下步骤: 1. 使用POI API创建工作簿、工作表等Excel对象。 2. 使用Freemarker模板引擎,将数据与Excel模板进行合并。 3. 将合并后的Excel文件写入磁盘,保存Excel文件。 以上就是Java导出Excel的三种方法,开发者们可以根据实际需求进行选择使用。需要注意的是,尽管以上三种方法的耗时都较少,容易操作,但还是存在相应的缺点和问题,需要我们在使用时认真考虑。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值