java jxl 导出 excel

pom

<dependency>
	<groupId>net.sourceforge.jexcelapi</groupId>
	<artifactId>jxl</artifactId>
	<version>2.6.12</version>
</dependency>

ExcelUtil.java

package com.common.util;

import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.read.biff.BiffException;
import jxl.write.*;
import jxl.write.biff.RowsExceededException;
import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ExcelUtil类<br>
 * <p>
 * 用于导入导出Excel
 * 
 */
public class ExcelUtil {

	@SuppressWarnings("deprecation")
	public static void WriteExcel(String templatePath, String title, int startRow, @SuppressWarnings("rawtypes") List dataList, OutputStream ops)
			throws BiffException, IOException, RowsExceededException, WriteException {
		WorkbookSettings settings = new WorkbookSettings();
		settings.setWriteAccess(null);
		Workbook wb = Workbook.getWorkbook(new File(templatePath));
		ByteArrayOutputStream targetFile = new ByteArrayOutputStream();
		WritableWorkbook wwb = Workbook.createWorkbook(targetFile, wb, settings);
		WritableSheet wws = wwb.getSheet(0);
		Label label = (Label) wws.getWritableCell(0, 0);
		WritableFont font = new WritableFont(WritableFont.createFont("宋体"), 10, WritableFont.NO_BOLD);
		WritableCellFormat cellFormat = new WritableCellFormat(font, NumberFormats.TEXT);
		label.setString(title);
		cellFormat.setWrap(true);
		cellFormat.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
		cellFormat.setAlignment(jxl.format.Alignment.CENTRE);
		cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN);

		for (int i = 0; i < dataList.size(); i++) {
			Object[] objs = (Object[]) dataList.get(i);
			for (int j = 0; j < objs.length; j++) {
				char newLine = 0x000A;
				if (objs[j] != null)
					wws.addCell(new Label(j, i + startRow, String.valueOf(objs[j]).replace(';', newLine), cellFormat));
				else
					wws.addCell(new Label(j, i + startRow, "", cellFormat));
			}
		}
		wwb.write();
		wwb.close();
		wb.close();
		targetFile.writeTo(ops);
		targetFile.close();
	}

	/**
	 * 根据传输的Excel内容取得第一个sheet中的内容
	 * 
	 * @param is
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public static Map ReadExcelToMap(final InputStream is) throws Exception {
		return ReadExcelToMap(is, 0);
	}

	/**
	 * 根据传输的Excel内容取得第sheetNum个sheet中的内容
	 * 
	 * @param is
	 * @param sheetNum
	 * @return Map
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map ReadExcelToMap(final InputStream is, final int sheetNum) throws Exception {
		Map returnMap = new HashMap();
		Map rowMap = new HashMap();
		// 工作表行数
		int rowNum;
		// 工作表列数
		int colNum;
		try {
			// 根据输入流创建Workbook对象
			Workbook wb = Workbook.getWorkbook(is);
			// 获得第sheetNum个工作表
			Sheet sheet = wb.getSheet(sheetNum);

			// sheet.getName();
			// 获得工作表行数
			rowNum = sheet.getRows();
			// 获得工作表列数
			colNum = sheet.getColumns();
			// 根据行数循环
			for (int i = 0; i < rowNum; i++) {
				rowMap = new HashMap();
				// 根据列数循环
				for (int j = 0; j < colNum; j++) {
					// System.out.println("i=" + i + "j=" + j);
					// 放入rowMap对象
					rowMap.put(String.valueOf(j), sheet.getCell(j, i).getContents());
				}
				// 将rowMap对象放入returnMap对象
				returnMap.put(String.valueOf(i), rowMap);
			}

		}
		// 捕捉异常
		catch (BiffException biffe) {
			biffe.printStackTrace();
			throw new RuntimeException(biffe.toString());
		}

		return returnMap;
	}

	public static String encodingFileName(String fileName) {
		String returnFileName = "";
		try {
			returnFileName = URLEncoder.encode(fileName, "UTF-8");
			returnFileName = StringUtils.replace(returnFileName, "+", "%20");
			if (returnFileName.length() > 150) {
				returnFileName = new String(fileName.getBytes("GB2312"), "ISO8859-1");
				returnFileName = StringUtils.replace(returnFileName, " ", "%20");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return returnFileName;
	}

	/**
	 * 描述:根据模板文件路径获取项目中的文件
	 * 
	 * @param fileDir
	 *            文件路径
	 * @return
	 * @throws Exception
	 */
	public static String getExcelTemplatePath(String fileDir) throws Exception {
		String classDir = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
		String fileBaseDir = classDir.substring(0, classDir.lastIndexOf("classes"));

		if (!new File(fileBaseDir + fileDir).exists()) {
			throw new Exception("模板文件不存在!");
		}
		return fileBaseDir + fileDir;
	}

}

调用

response.setHeader("Content-Disposition", "attachment; filename=" + ExcelUtil.encodingFileName("信息_"+deviceSn+".xls"));
ExcelUtil.WriteExcel(ExcelUtil.getExcelTemplatePath("/excel_template/lack_detail.xls"), "信息 "+deviceSn, 2, listObj, response.getOutputStream());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值