`
kanpiaoxue
  • 浏览: 1789492 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

生成Excel / 读取Excel

 
阅读更多

我们常常需要在web中导出excel。

这里给出一个方法,采用poi的框架,生成excel。用response打出到web页面。

	/**
	 * <pre>
	 * 导出excel工具方法
	 * 
	 * @author kanpiaoxue 
	 * date 2011-09-02
	 * @param response
	 * @param datas
	 *            数据
	 * @param sheetName
	 *            sheet的名字
	 * 
	 *            [备注] 默认带有excel导出的名字。就是当日的日期和时间的组合:2011-09-02_08_37_35.xls
	 * 需要 org.apache.poi 的jar包
	 × google的 guava.jar
	 * </pre>
	 */
	public static void exportExcelUtil(HttpServletResponse response,
			List<List<String>> datas, String sheetName) {

		checkNotNull(response);
		checkNotNull(datas);
		checkArgument(!StringUtils.isEmpty(sheetName),
				"sheetName is empty or null!");

		class ExcelTool {
			public HSSFCellStyle getTitleStyle(HSSFWorkbook wb) {
				HSSFCellStyle style = wb.createCellStyle();
				style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 标题居中对齐
				style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
				style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
				style.setFillForegroundColor(HSSFColor.PALE_BLUE.index);
				style.setBorderTop(HSSFCellStyle.BORDER_THIN);
				style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
				style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
				style.setBorderRight(HSSFCellStyle.BORDER_THIN);
				style.setWrapText(true);
				return style;
			}

			private HSSFCellStyle getStringStyle(HSSFWorkbook wb) {
				// create cell style
				HSSFCellStyle style = wb.createCellStyle();
				// set the style of cell
				style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);// 数据右对齐
				style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
				style.setBorderTop(HSSFCellStyle.BORDER_THIN);
				style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
				style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
				style.setBorderRight(HSSFCellStyle.BORDER_THIN);
				style.setWrapText(true);
				return style;
			}
		}

		ExcelTool excelTool = new ExcelTool();
		// create the excel work book
		HSSFWorkbook wb = new HSSFWorkbook();
		// create the sheet
		HSSFSheet sheet = wb.createSheet(sheetName);

		// get the style of title cell
		HSSFCellStyle titleStyle = excelTool.getTitleStyle(wb);
		HSSFCellStyle dataStyle = excelTool.getStringStyle(wb);

		int i = 0;
		for (List<String> innerList : datas) {
			HSSFCellStyle tmpStyle = dataStyle;
			HSSFRow row = sheet.createRow(i);
			if (i == 0) {// table header
				row.setHeight((short) 500);
				tmpStyle = titleStyle;
			}
			int j = 0;
			for (String str : innerList) {
				HSSFCell cell = row.createCell(j);
				cell.setCellStyle(tmpStyle);
				cell.setCellValue(new HSSFRichTextString(str));
				sheet.setColumnWidth(j, 6000);
				j++;
			}
			i++;
		}

		response.reset();
		response.setContentType("application/vnd.ms-excel; charset=utf8");
		response.setHeader("Content-Disposition",
				"attachment; filename="
						+ XPDateUtils.formatDateSecondLongPattern(new Date())
								.replaceAll("-", "_").replaceAll(":", "_")
								.replaceAll(" ", "_") + ".xls");
		OutputStream out = null;
		try {
			out = response.getOutputStream();
			wb.write(out);
		} catch (IOException e) {
			LOGGER.error("Exception: download excel " + e.getMessage(), e);
		} finally {
			IOUtils.closeQuietly(out);
		}
	}

 为了日常使用,我把web导出Excel稍微的改装了一下,形成本地File文件的excel导出。

package org.kanpiaoxue.staticClass;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.util.IOUtils;

import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.io.Files;

public class ExportExcell {
	private static final Logger LOGGER = Logger.getLogger(ExportExcell.class);

	public static void main(String[] args) throws Exception {
		testStaticClass();
	}

	public static void testStaticClass() throws Exception {
		String dir = System.getProperty("user.dir")
				+ "/src/org/kanpiaoxue/staticClass/file" + File.separator;
		String inputFileName = dir + "编辑1.txt";
		String outputFileName = dir + "export.xls";
		System.out.println(dir);
		File file = new File(inputFileName);
		List<String> lines = Files.readLines(file, Charset.forName("utf-8"));
		List<List<String>> rs = Lists.newArrayList();
		for (String line : lines) {
			List<String> lst = Splitter.on(' ').omitEmptyStrings()
					.trimResults().splitToList(line);
			if (CollectionUtils.isEmpty(lst)) {
				continue;
			}
			System.out.println(lst);
			rs.add(lst);
		}

		exportExcelUtil(new FileOutputStream(new File(outputFileName)), rs,
				"hello");
	}

	/**
	 * <pre>
	 * 导出excel工具方法
	 * 
	 * @author kanpiaoxue 
	 * date 2011-09-02
	 * @param response
	 * @param datas
	 *            数据
	 * @param sheetName
	 *            sheet的名字
	 * 
	 *            [备注] 默认带有excel导出的名字。就是当日的日期和时间的组合:2011-09-02_08_37_35.xls
	 * 需要 org.apache.poi 的jar包
	 * 	 × google的 guava.jar
	 * </pre>
	 */
	public static void exportExcelUtil(OutputStream fileOutputStream,
			List<List<String>> datas, String sheetName) {

		Preconditions.checkNotNull(fileOutputStream);
		Preconditions.checkNotNull(datas);
		Preconditions.checkArgument(!StringUtils.isEmpty(sheetName),
				"sheetName is empty or null!");

		class ExcelTool {
			public HSSFCellStyle getTitleStyle(HSSFWorkbook wb) {
				HSSFCellStyle style = wb.createCellStyle();
				style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 标题居中对齐
				style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
				style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
				style.setFillForegroundColor(HSSFColor.PALE_BLUE.index);
				style.setBorderTop(HSSFCellStyle.BORDER_THIN);
				style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
				style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
				style.setBorderRight(HSSFCellStyle.BORDER_THIN);
				style.setWrapText(true);
				return style;
			}

			private HSSFCellStyle getStringStyle(HSSFWorkbook wb) {
				// create cell style
				HSSFCellStyle style = wb.createCellStyle();
				// set the style of cell
				style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);// 数据右对齐
				style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
				style.setBorderTop(HSSFCellStyle.BORDER_THIN);
				style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
				style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
				style.setBorderRight(HSSFCellStyle.BORDER_THIN);
				style.setWrapText(true);
				return style;
			}
		}

		ExcelTool excelTool = new ExcelTool();
		// create the excel work book
		HSSFWorkbook wb = new HSSFWorkbook();
		// create the sheet
		HSSFSheet sheet = wb.createSheet(sheetName);

		// get the style of title cell
		HSSFCellStyle titleStyle = excelTool.getTitleStyle(wb);
		HSSFCellStyle dataStyle = excelTool.getStringStyle(wb);

		int i = 0;
		for (List<String> innerList : datas) {
			HSSFCellStyle tmpStyle = dataStyle;
			HSSFRow row = sheet.createRow(i);
			if (i == 0) {// table header
				row.setHeight((short) 500);
				tmpStyle = titleStyle;
			}
			int j = 0;
			for (String str : innerList) {
				HSSFCell cell = row.createCell(j);
				cell.setCellStyle(tmpStyle);
				cell.setCellValue(new HSSFRichTextString(str));
				sheet.setColumnWidth(j, 6000);
				j++;
			}
			i++;
		}

		try {
			wb.write(fileOutputStream);
		} catch (IOException e) {
			LOGGER.error("Exception: download excel " + e.getMessage(), e);
		} finally {
			IOUtils.closeQuietly(fileOutputStream);
		}
	}

	public static String formatDateSecondLongPattern(Date date) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(date);
	}

}

 

 读取Excel

	/**
	 * <pre>
	 * @param fileName
	 * @return 读取Excel的内容
	 * </pre>
	 */
	public static List<List<String>> readExcel(String fileName)
			throws Exception {
		// EXCEL_SUFFIX
		checkArgument(!Strings.isNullOrEmpty(fileName),
				"fileName is null or empty!");
		fileName = fileName.trim();
		checkArgument(fileName.endsWith(EXCEL_SUFFIX), "fileName not endsWith "
				+ EXCEL_SUFFIX);

		InputStream inputStream = new FileInputStream(new File(fileName));

		return readExcel(inputStream);
	}

	/**
	 * <pre>
	 * @param fileName
	 * @return 读取Excel的内容
	 * </pre>
	 */
	public static List<List<String>> readExcel(InputStream inputStream)
			throws Exception {

		List<List<String>> rsList = newArrayList();
		try {

			POIFSFileSystem fs = new POIFSFileSystem(inputStream);
			HSSFWorkbook wb = new HSSFWorkbook(fs);

			HSSFSheet sheet = wb.getSheetAt(0);
			// 得到总行数
			int rowNum = sheet.getLastRowNum();
			for (int i = 0; i <= rowNum; i++) {
				List<String> rowDatas = newArrayList();
				HSSFRow row = sheet.getRow(i);
				int colNum = row.getPhysicalNumberOfCells();
				for (int j = 0; j < colNum; j++) {
					rowDatas.add(getCellFormatValue(row.getCell(j)));
				}
				rsList.add(rowDatas);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(inputStream);
		}
		return rsList;
	}

	/**
	 * 根据HSSFCell类型设置数据
	 * 
	 * @param cell
	 * @return
	 */
	private static String getCellFormatValue(HSSFCell cell) {
		String cellvalue = "";
		if (cell != null) {
			// 判断当前Cell的Type
			switch (cell.getCellType()) {
			// 如果当前Cell的Type为NUMERIC
			case HSSFCell.CELL_TYPE_NUMERIC:
			case HSSFCell.CELL_TYPE_FORMULA: {
				// 判断当前的cell是否为Date
				if (HSSFDateUtil.isCellDateFormatted(cell)) {
					// 如果是Date类型则,转化为Data格式
					Date date = cell.getDateCellValue();
					cellvalue = XPDateUtils.formatDateSecondLongPattern(date);

				}
				// 如果是纯数字
				else {
					// 取得当前Cell的数值
					cellvalue = String.valueOf(cell.getNumericCellValue());
				}
				break;
			}
			// 如果当前Cell的Type为String
			case HSSFCell.CELL_TYPE_STRING:
				// 取得当前的Cell字符串
				cellvalue = cell.getRichStringCellValue().getString();
				break;
			// 默认的Cell值
			default:
				cellvalue = "";
			}
		}
		return cellvalue;

	}

 

分享到:
评论

相关推荐

    golang实现的读取excel模板批量生成excel工具.zip

    本项目"golang实现的读取excel模板批量生成excel工具"正是基于这一需求而设计的,它允许用户通过读取一个Excel模板来快速创建多个类似的Excel文件。 首先,我们来看这个工具的核心技术点。在Go中,处理Excel文件...

    NOPI导出EXCEL/xls/xlsx并输出到WEB页面

    1. **导入Excel(xls/xlsx)**:NOPI提供了一个接口或者API,使得开发者可以读取Excel文件的内容,无论是旧版的.xls格式还是较新的.xlsx格式。这通常涉及到解析Excel文件的结构,获取工作表、单元格的数据,并将其...

    excel生成和读取

    本文将详细讲解如何在编程环境中生成和读取Excel文件,以实现自动化处理和分析大量数据。 首先,我们要理解的是,生成Excel文件通常涉及到使用编程语言中的特定库或模块。在Python中,我们有pandas库配合openpyxl或...

    Java生成excel 和读取word文档的内容 jxl 代码

    在Java编程中,生成Excel和读取Word文档是常见的任务,尤其在数据处理、报告生成或数据导出等场景中。这里我们将详细讨论如何使用jxl库来完成这些任务。 首先,jxl是一个广泛使用的开源Java库,它允许开发者方便地...

    EXCEL生成与读取

    1. **生成Excel文件**: - 创建工作簿:使用`Workbook.createWorkbook()`方法创建一个新的Excel工作簿对象。 - 添加工作表:调用`Workbook`对象的`createSheet()`方法,传入工作表名称即可创建新工作表。 - 写入...

    POI生成Excel POI操作Excel POI读取Excel POI类库

    你需要创建一个Servlet,然后在doGet或doPost方法中调用上述生成Excel的逻辑,并设置响应头以指示内容类型为"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",以及设置Content-Disposition为...

    QT Excel处理开源项目,github地址:https://github.com/QtExcel/QXlsx

    QT Excel处理开源项目QXlsx是一个基于Qt框架的库,专为在C++环境中操作Excel文件而设计。这个项目提供了一种高效且易于使用的接口,...通过熟悉和掌握QXlsx,你可以更高效地完成数据管理、报表生成以及数据分析等工作。

    vb6.0实现,读取access处理业务数据,生成excel文档

    在这个项目中,我们探讨了如何利用Visual Basic 6.0(VB6.0)来读取Access数据库中的数据,并进行业务逻辑处理,最终生成Excel文档以便于分析、报表生成或共享。 首先,我们需要引入Microsoft DAO 3.6 Object ...

    java的poi生成excel图表demo

    在Java中,它允许开发者创建、修改和读取Excel工作簿、工作表以及单元格的数据。POI库不仅支持基本的文本和数字操作,还支持更高级的功能,如公式计算、样式设置和图表创建。 2. **创建Excel图表** 要生成Excel图表...

    读取Doc,Excel,PDF,html,生成Txt文件,读取Txt生成Excel文件 jar

    读取Doc,Excel,PDF,html,生成Txt文件,读取Txt生成Excel文件 jar 所需用的jar文件: fontbox-0.1.0.jar PDFBox-0.7.3.jar poi-3.0.1.jar tm-extractors-0.4.jar

    excel读取生成xml文件

    本文将详细介绍如何通过Excel读取数据并生成XML文件,以实现数据的标准化存储和传输。 首先,我们需要了解Excel如何读取数据。Excel提供了丰富的函数和公式,可以方便地对单元格中的数据进行操作。例如,VLOOKUP...

    java poi 根据excel模板生成excel文件

    在Java中,我们可以使用POI API来读取模板文件,然后在模板的基础上填充自定义数据,生成新的Excel文件。 1. **安装和引入POI库** 在Java项目中使用POI,你需要将`poi-ooxml`相关的JAR文件添加到项目的类路径中。...

    读取EXCEL,读取EXCEL,读取EXCEL,读取EXCEL

    在IT领域,读取Excel是一项常见的任务,尤其在数据分析、报表处理和自动化脚本中。Excel文件(.xlsx或.xls)通常包含表格数据,而Python编程语言提供了多种库来处理这些文件。本篇文章将深入探讨如何使用Python读取...

    Java通过POI读取Excel遍历数据,批量生成word文档

    本教程将重点讲解如何使用Apache POI库来读取Excel数据,并基于这些数据批量生成Word文档。Apache POI是一个开源项目,它允许Java开发者处理Microsoft Office格式的文件,如Excel(.xlsx或.xls)和Word(.docx)。 ...

    java jxl创建/读取/修改Excel 操作Excel

    读取Excel文件的操作相对简单,你只需创建一个`Workbook`对象并遍历其工作表和单元格。例如: ```java Workbook workbook = Workbook.getWorkbook(new File("input.xls")); Sheet sheet = workbook.getSheet(0); for...

    C# 生成和读取EXCEL文件

    本主题聚焦于如何使用C#来生成和读取Excel文件,这在数据处理和报告生成等领域非常常见。Excel文件(.xlsx)通常采用Microsoft Office的Open XML格式,这种格式允许开发者使用XML解析器或特定库来操作文件内容。 ...

    JAVA读取Excel,建库建表,并生成java实体

    总结,Java读取Excel并进行数据库建库建表及生成Java实体的过程涉及了Apache POI库的使用、数据库操作和源代码生成。理解这些步骤可以帮助你有效地处理类似的任务,提高开发效率。在实际应用中,你还需要考虑错误...

    java读取excel文件生成矩阵

    在Java编程中,读取Excel文件并生成矩阵是一项常见的任务,尤其在数据分析、报表处理或者数据导入导出的场景下。Excel文件通常用于存储结构化的表格数据,而矩阵则是一种有效的数据表示方式,便于计算和分析。下面...

    NPOI操作excel之读取、写入excel数据

    // 读取Excel代码... return Ok("数据读取成功"); } [HttpPost] public IActionResult WriteExcel([FromBody] List[]&gt; data) { // 写入Excel代码... return Ok("数据写入成功"); } ``` NPOI还支持更复杂的功能...

    java 根据简单对象自动 生成excel

    在Java编程中,生成Excel文件是一项常见的任务,特别是在数据导出、报告生成或者数据分析场景下。本示例探讨的是如何利用反射和简单的对象模型来自动创建Excel文件。这个项目的核心思想是通过对象的属性(字段)及其...

Global site tag (gtag.js) - Google Analytics