`
julianyuan
  • 浏览: 6488 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
文章分类
社区版块
存档分类
最新评论

Excel的导入与导出

    博客分类:
  • Java
阅读更多

由于公司的很多系统都是好多年前做的,在公司的Office升级完成以后,公司内部的系统对新版本的Excel支持问题就一一浮现出来。越来越多的人在抱怨公司内部对excel2007和2010不支持的问题。最近研究了一下java对excel的操作,发现使用现有的工具对excel2007和2010的支持并不是那么难,现将自己的心得分享出来。

 

所需的jar包: Jxls-core 1.0.5, Poi 3.10, Poi-ooxml 3.10, Poi-ooxml-schemas 3.10, Commons-beanutils 1.9.2, Commons-digister 2.0, Commons-jexl 2.1.1, Commons-logging 1.1.3, Xmlbeans 2.3。

 

公司内部使用的SSH架构。

 

导出:

这里使用jxls包,使用excel template来导出文件。官网:http://jxls.sourceforge.net/index.html

excel template的写法请参照官网,下面是导出excel的代码,导出的excel版本根据你创建template的版本来定:

 

package com.apps.core.struts.dispatcher;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.io.PushbackInputStream;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import net.sf.jxls.transformer.XLSTransformer;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.StrutsResultSupport;

import com.opensymphony.xwork2.ActionInvocation;

public class ExcelResult extends StrutsResultSupport {

	private static final long serialVersionUID = 462425636352447077L;
	private static final String contentTypeXls = "application/vnd.ms-excel";
	private static final String contentTypeXlsx = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    private static final String actionKey = "action";

    private boolean multiSheet = false;
    private String listName;
    private String sheetName;
    private String beanName;
    
	@Override
	protected void doExecute(String location,
			ActionInvocation invocation) throws Exception {
        HttpServletResponse response = ServletActionContext.getResponse();

        response.reset();
        
        Workbook workbook;
        InputStream in = null;
        //这里对excel版本的判断借鉴与POI-OOXML包里的方法
        try {
            in = this.getTemplate(location, ServletActionContext.getServletContext());
            //check the file support mark or reset function
			if (!in.markSupported()) {
				in = new PushbackInputStream(in, 8);
			}
			
			XLSTransformer transformer = new XLSTransformer();
            Map<String, Object> beans = PropertyUtils.describe(invocation.getAction());
            beans.put(actionKey, invocation.getAction());
            
            //check input file type
            //for excel 2003
			if (POIFSFileSystem.hasPOIFSHeader(in)) {
		        response.setContentType(contentTypeXls);
	            //we use action name plus timestamp as the filename
	            response.setHeader("Content-Disposition", "attachment; filename=\"" + invocation.getProxy().getActionName() + "_" + System.currentTimeMillis()
	            			+ ".xls\"");
			}
			//for excel 2007,2010
			else if (POIXMLDocument.hasOOXMLHeader(in)) {
		        response.setContentType(contentTypeXlsx);
		        //we use action name plus timestamp as the filename
	            response.setHeader("Content-Disposition", "attachment; filename=\"" + invocation.getProxy().getActionName() + "_" + System.currentTimeMillis()
	            			+ ".xlsx\"");
			}
			//exception
			else{
				throw new Exception("Your InputStream was neither an OLE2 stream, nor an OOXML stream");
			}
			
			//transform workbook
            if (multiSheet) {
                workbook = transformer.transformMultipleSheetsList(in, (List<?>) invocation.getStack().findValue(listName), (List<?>) invocation.getStack()
                        .findValue(sheetName), beanName, beans, 0);
            } else {
                workbook = transformer.transformXLS(in, beans);
            }
            //output
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
        } finally {
            if (in != null) {
                in.close();
            }
        }
	}

    protected InputStream getTemplate(String location, ServletContext servletContext) {
        return servletContext.getResourceAsStream(location);
    }


    //getters and setters
    public boolean isMultiSheet() {
        return multiSheet;
    }

    public void setMultiSheet(boolean multiSheet) {
        this.multiSheet = multiSheet;
    }

    public String getBeanName() {
        return beanName;
    }

    public void setBeanName(String beanName) {
        this.beanName = beanName;
    }

    public String getListName() {
        return listName;
    }

    public void setListName(String listName) {
        this.listName = listName;
    }

    public String getSheetName() {
        return sheetName;
    }

    public void setSheetName(String sheetName) {
        this.sheetName = sheetName;
    }
}

 

 

读取:

返回类型是Workbook,得到Workbook后再根据自己的需要读取其中的内容。

 

package com.apps.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelReadUtils {

	public Workbook excelRead(InputStream in) {
		
		if (!in.markSupported()) {
			in = new PushbackInputStream(in, 8);
		}
		
        //check input file type
        //for excel 2003
		try {
			if (POIFSFileSystem.hasPOIFSHeader(in)) {
			    HSSFWorkbook hssfWorkbook = new HSSFWorkbook(in);
			    return hssfWorkbook;
			}
			//for excel 2007,2010
			else if (POIXMLDocument.hasOOXMLHeader(in)) {
				XSSFWorkbook xssfWorkbook = new XSSFWorkbook(in);
				return xssfWorkbook;
			}
			//exception
			else{
				throw new Exception("Your InputStream was neither an OLE2 stream, nor an OOXML stream");
			}
		} catch (IOException e) {
			throw new Exception("Open excel file error.");
		}finally{
            if (in != null) {
                try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
            }
		}
	}
	
	public Workbook excelRead(String path){
		InputStream in;
		try {
			in = new FileInputStream(path);
			return excelRead(in);
		} catch (FileNotFoundException e) {
			throw new Exception("The file not exists. Path: "+path);
		}
	}
	
	public Workbook excelRead(File file){
		InputStream in;
		try {
			in = new FileInputStream(file);
			return excelRead(in);
		} catch (FileNotFoundException e) {
			throw new Exception("The file not exists. Path: "+file.getAbsolutePath());
		}
	}
}

 

 

分享到:
评论

相关推荐

    基于Aspose.Cell的Excel导入与导出 程序源码

    在这个基于Aspose.Cell的项目中,我们看到的"基于Aspose.Cell的Excel导入与导出程序源码"显然涉及到如何在Windows Forms(winform)应用程序中读取、修改和保存Excel工作簿的操作。 首先,我们需要了解Aspose.Cell...

    C#Excel导入与导出实例

    3. **Office Interop组件**:传统的Excel导入导出方法通常会使用Office Interop组件,这是微软提供的用于与Office应用程序进行交互的接口。但请注意,这种方式并不适用于服务器环境,因为它需要安装完整版的Office,...

    jsp网站 实现Excel导入与导出功能.zip

    实现Excel导入与导出功能,并WEB页面附带进度条对Excel进行美化如:设置背景色、线条、格子大小等。 使用步骤很简单 1.解压下载好的项目,这里需要进行基本配置如Maven配置,本项目中使用的是jdk 1.8。 2.启动...

    delphi中excel导入与导出实例

    在Delphi编程环境中,处理Excel数据是一项常见的任务,这通常涉及到数据的导入和导出功能。本实例将探讨如何在Delphi中实现Excel文件的读取和写入操作,以便于数据交换和处理。 首先,我们需要了解Delphi中用于与...

    简易网站 实现Excel导入与导出功能.rar

    首先,我们要了解Excel导入与导出的基本原理。Excel文件通常是以逗号分隔值(CSV)或二进制格式(如.xlsx或.xls)存储的,这两种格式都能被编程语言读取和写入。在Web应用中,我们通常使用JavaScript的库,如Papa ...

    excel导入与导出原码

    本文将深入探讨“Excel导入与导出原码”这一主题,主要关注如何通过编程方式实现Excel数据的读取与写入。 首先,我们需要了解两种常用的语言库:Python中的`pandas`和`openpyxl`,以及Java中的`Apache POI`。`...

    Thinkphp5整合excel导入导出

    Thinkphp5整合excel导入导出Thinkphp5整合excel导入导出Thinkphp5整合excel导入导出Thinkphp5整合excel导入导出Thinkphp5整合excel导入导出Thinkphp5整合excel导入导出Thinkphp5整合excel导入导出Thinkphp5整合excel...

    thinkhphp3.2 excel导入导出demo

    thinkhphp3.2 excel导入导出demothinkhphp3.2 excel导入导出demothinkhphp3.2 excel导入导出demothinkhphp3.2 excel导入导出demothinkhphp3.2 excel导入导出demothinkhphp3.2 excel导入导出demothinkhphp3.2 excel...

    SpringBoot使用poi实现Excel导入与导出

    在SpringBoot应用中,使用Apache POI库可以方便地实现Excel的导入与导出功能。Apache POI是一个流行的API,它允许程序员创建、修改和显示Microsoft Office格式的文件,其中包括Excel(.xls和.xlsx)文件。在这个场景...

    EXCEL数据导入与导出.rar

    EXCEL数据导入与导出.rar EXCEL数据导入与导出.rar EXCEL数据导入与导出.rar EXCEL数据导入与导出.rar EXCEL数据导入与导出.rar EXCEL数据导入与导出.rar

    Excel导入导出项目 简单的

    Excel导入导出Excel导入导出Excel导入导出Excel导入导出Excel导入导出Excel导入导出Excel导入导出Excel导入导出Excel导入导出Excel导入导出Excel导入导出Excel导入导出

    asp将EXCEL导入导出数据库原程序

    这个"asp将EXCEL导入导出数据库原程序"提供了一个解决方案,能够方便地将Excel中的数据存入MSSQL数据库,同时也能将数据库中的数据导出到Excel文件。 首先,我们需要了解如何使用ASP连接MSSQL数据库。通常,这涉及...

    使用Springboot实现excel的导入导出

    在Spring Boot中实现Excel的导入导出可以通过POI库来实现,POI是一个开源的Java库,用于处理Microsoft Office格式文件,包括Excel。一个简单的示例,演示如何在Spring Boot项目中使用POI来实现Excel的导入导出功能。...

    Java POI EXCEL导入导出

    Java POI EXCEL导入导出Java POI EXCEL导入导出Java POI EXCEL导入导出Java POI EXCEL导入导出Java POI EXCEL导入导出Java POI EXCEL导入导出Java POI EXCEL导入导出Java POI EXCEL导入导出Java POI EXCEL导入导出...

    CS开发常用功能-从Excel导入与导出(收集了很多代码)

    在CS(Client-Side,客户端)开发中,从Excel导入数据到应用程序是一个常见的需求,尤其在数据处理和管理中。这段代码示例是用于Lotus Notes应用中的,它展示了如何利用VBA(Visual Basic for Applications)来实现...

    Java实现Excel导入导出

    Excel源代码,导入导出各种工具类 &lt;groupId&gt;org.apache.poi &lt;artifactId&gt;poi &lt;groupId&gt;org.apache.poi &lt;artifactId&gt;poi-scratchpad 代码实例: String path = ""; byte[] bytes; vo.setCurrentPage(0); vo....

    普元导入导出用于Excel导入导出

    在"普元导入导出 EOS 用于Excel导入导出"的场景下,我们可以探讨以下几个关键知识点: 1. **数据导入导出**: 这是系统与用户间交互的重要方式,允许用户通过Excel这样的工具来编辑和管理数据,然后将这些更改同步到...

    springboot实现Excel文件导入与导出功能

    springboot实现Excel文件导入与导出功能, 本次任务主要实现两个功能,一是如何将Excel文件导入后台服务器,解析文件中的内容,并且存入数据库中。二是如何将后台数据库中的数据导出为Excel表格。经过调研,实现此...

    java_poi实现excel导入导出

    Java POI 实现 Excel 导入导出 Java POI 是一个流行的 Java 库,用于处理 Microsoft Office 文件格式,包括 Excel 文件。在本文中,我们将详细介绍如何使用 Java POI 实现 Excel 导入导出功能。 1. 什么是 Java ...

    Excel导入导出 Excel导入 Excel导出

    "Excel导入导出"这一主题涵盖了如何将数据从外部源引入Excel以及如何将Excel数据导出到其他应用程序或格式。以下是对这一主题的详细解释: 1. **Excel导入**: - **CSV文件导入**:CSV(Comma Separated Values)...

Global site tag (gtag.js) - Google Analytics