search
HomeDatabaseMysql Tutorial使用POI将Mysql或Oracle中的数据导入到Excel中去_MySQL

在我们实际的开发中,表现层的解决方案虽然有多样,但是IE浏览器已成为最多人使用的浏览器,因为大家都用Windows。在企业办公系统中,常常有客户这样子要求:你要把我们的报表直接用Excel打开。或者是:我们已经习惯用Excel打印。这样子如果用.net开发是没有问题的,.net用来进行这些数据导入导出支持的都是很好,如果你使用的是SQL Server数据库那就更方便了,笔者也曾体会到.net开发这些功能的方便性.但是有j2ee这个比.net更有前途的开放式的开发环境,难道我为了解决打印的要求去另写客户端的控件?或者在服务器端使用本地代码?第一种方案的问题是关键数据的处理有时候不能在客户端做,第2种方案的问题是牺牲了代码的可移植性和稳定性。如果让客户端只负责处理生成好的报表,那将是一种诱人的选择。

    Apache的Jakata项目的POI子项目,目标是处理ole2对象。目前比较成熟的是HSSF接口,处理MS Excel(97-2002)对象。它不象我们仅仅是用csv生成的没有格式的可以由Excel转换的东西,而是真正的Excel对象,你可以控制一些属性如sheet,cell等等。这是一个年轻的项目,所以象HDF这样直接支持Word对象的好东西仍然在设计中。其它支持word格式的纯java方案还有itext,不过也是仍在奋斗中。但是HSSF已经成熟到能够和足够我们使用了。另外,无锡永中Office的实现方案也是纯java的解决方案,不过那也是完全商业的产品,并不是公开代码项目。其实,从开发历史的角度讲,在80年代中期starOffice的原作者在德国成立了StarOffice suite公司,然后到1999年夏天starOffice被sun收购,再到2000年6月starOffice5.2的发布;并且从starOffice6.0开始,starOffice建立在OpenOffice的api的基础上,这个公开代码的office项目已经进行了很长的时间。虽然那是由C++写的,但是POI的代码部分也是由openOffice改过来的。所以,应该对POI充满足够的信心。国内已经有部分公司在他们的办公自动化等Web项目中使用poi了,如日恒的ioffice,海泰的HTOffice等。

    java当初把核心处理设成Unicode,带来的好处是另代码适应了多语言环境。然而由于老外的英语只有26个字母,有些情况下,一些程序员用8位的byte处理,一不小心就去掉了CJK的高位。或者是由于习惯在程序中采用硬编码,还有多种原因,使得许多java应用在CJK的处理上很烦恼。还好在POI HSSF中考虑到这个问题,可以设置encoding为双字节。

    POI可以到www.apache.org下载到。编译好的jar主要有这样4个:poi包,poi Browser包,poi hdf包,poi hssf例程包。实际运行时,需要有poi包就可以了。如果用Jakarta ant编译和运行,下载apache Jakarta POI的release中的src包,它里面已经为你生成好了build文件了。只要运行ant就可以了(ant 的安装和使用在此不说了)。如果是用Jbuilder 运行,请在新建的项目中加入poi包。以Jbuilder6为例,选择Tools菜单项的config libraries...选项,新建一个lib。在弹出的菜单中选择poi包,如这个jakarta-poi-1.5.1-final-20020820.jar,把poi添加到jbuilder中。然后,右键点击你的项目,在project的properties菜单中path的required Libraries中,点add,添加刚才加入到jbuilder中的poi到你现在的项目中。如果你仅仅是为了熟悉POI hssf的使用,可以直接看POI的samples包中的源代码,并且运行它。hssf的各种对象都有例程的介绍。hssf提供的例程在org.apache.poi.hssf.usermodel.examples包中,共有14个,生成的目标xls都是workbook.xls。如果你想看更多的例程,可以参考hssf的Junit test cases,在poi的包的源代码中有。hssf都有测试代码。
   
    首先,到http://apache.justdn.org/jakarta/poi/release/bin/上去下载POI,登录到该网址以后,选择红色区域的poi-bin-2.5.1-final-20040804.zip来下载

使用POI将Mysql或Oracle中的数据导入到Excel中去(图一)

下载以后解压,解压目录为
使用POI将Mysql或Oracle中的数据导入到Excel中去(图二)

 在Eclipse中设置对poi-bin-2.5.1-final-20040804.jar的库引用.
    在Eclipse中新建一个名字叫POIExcel的Java工程,右键POIExcel项目的项目名,选择Build Path,再选择Add External Archives,然后找到poi-bin-2.5.1-final-20040804.jar这个包将其引进到工程中来.

    Excel 结构
    HSSFWorkbook excell 文档对象介绍
    HSSFSheet excell的表单
    HSSFRow excell的行
    HSSFCell excell的格子单元
    HSSFFont excell字体
    HSSFName 名称
    HSSFDataFormat 日期格式
    辅助操作包括
    HSSFDateUtil 日期
    HSSFPrintSetup 打印
    HSSFErrorConstants 错误信息表

    将数据导出到Excel中的实例

    1. 创建一个空白的Excel文件
    我们创建一个最普通的Java应用程序即可,程序代码如下: HSSFWorkbook wb=new HSSFWorkbook();
FileOutputStream fileout = new FileOutputStream("C://test.xls");
wb.write(fileout);
fileout.close();
    FileOutputStream属于JDK的数据流对象,通过它来将一个名为test.xls文件创建在C盘根目录下,运行该程序后可以看到在C盘上的根目录上多了一个Excel文件.
    如果将程序中的FileOutputStream("C://test.xls")的参数改为"test.xls",则文件就会创建在该项目的根目录下.

    2. 往Excel的单元格中写入信息
    POI把Excel分解成几个对象,自顶向下的关系是:工作薄(HSSFWorkbook)->表格(HSSFSheet)->表格行(HSSFRow)->单元格(HSSFCell).将数据库中表的数据导入到Excel中,首先我们要将数据库中的表的数据查询出来,这里我们通过Hibernate来将数据库中addressbook_table表的数据查询出来.然后通过循环将表中的数据导入到Excel中去. HSSFWorkbook wb=new HSSFWorkbook();
HSSFSheet sheet=wb.createSheet("new sheet");
try ...{
//通过Hibernate来查询addressbook_table表中的数据,将其存储在List中
    Transaction tx = session.beginTransaction();
    org.hibernate.Query query= session.createQuery("from AddressbookTable");
    List list = query.list();
    tx.commit();
    int k =0;

//创建表格,创建表格行和单元格,将数据库中表的字段存储在单元格中.
    for(Iterator it=list.iterator();it.hasNext();)...{
        AddressbookTable user =(AddressbookTable)it.next();
        HSSFRow row=sheet.createRow((short)k);
        row.createCell((short)0).setCellValue(user.getId());
        row.createCell((short)1).setCellValue(user.getName());
        row.createCell((short)2).setCellValue(user.getAddress());
        row.createCell((short)3).setCellValue(user.getPhone());
        k++;
    }

    FileOutputStream fileout = new FileOutputStream("C://test.xls");
    wb.write(fileout);
    fileout.close();


    log.error("Successful!!");
    } catch (HibernateException e) ...{
        log.error("Insert Exception!");
        e.printStackTrace();
    }

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL's Role: Databases in Web ApplicationsMySQL's Role: Databases in Web ApplicationsApr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

MySQL: Building Your First DatabaseMySQL: Building Your First DatabaseApr 17, 2025 am 12:22 AM

The steps to build a MySQL database include: 1. Create a database and table, 2. Insert data, and 3. Conduct queries. First, use the CREATEDATABASE and CREATETABLE statements to create the database and table, then use the INSERTINTO statement to insert the data, and finally use the SELECT statement to query the data.

MySQL: A Beginner-Friendly Approach to Data StorageMySQL: A Beginner-Friendly Approach to Data StorageApr 17, 2025 am 12:21 AM

MySQL is suitable for beginners because it is easy to use and powerful. 1.MySQL is a relational database, and uses SQL for CRUD operations. 2. It is simple to install and requires the root user password to be configured. 3. Use INSERT, UPDATE, DELETE, and SELECT to perform data operations. 4. ORDERBY, WHERE and JOIN can be used for complex queries. 5. Debugging requires checking the syntax and use EXPLAIN to analyze the query. 6. Optimization suggestions include using indexes, choosing the right data type and good programming habits.

Is MySQL Beginner-Friendly? Assessing the Learning CurveIs MySQL Beginner-Friendly? Assessing the Learning CurveApr 17, 2025 am 12:19 AM

MySQL is suitable for beginners because: 1) easy to install and configure, 2) rich learning resources, 3) intuitive SQL syntax, 4) powerful tool support. Nevertheless, beginners need to overcome challenges such as database design, query optimization, security management, and data backup.

Is SQL a Programming Language? Clarifying the TerminologyIs SQL a Programming Language? Clarifying the TerminologyApr 17, 2025 am 12:17 AM

Yes,SQLisaprogramminglanguagespecializedfordatamanagement.1)It'sdeclarative,focusingonwhattoachieveratherthanhow.2)SQLisessentialforquerying,inserting,updating,anddeletingdatainrelationaldatabases.3)Whileuser-friendly,itrequiresoptimizationtoavoidper

Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Apr 16, 2025 am 12:20 AM

ACID attributes include atomicity, consistency, isolation and durability, and are the cornerstone of database design. 1. Atomicity ensures that the transaction is either completely successful or completely failed. 2. Consistency ensures that the database remains consistent before and after a transaction. 3. Isolation ensures that transactions do not interfere with each other. 4. Persistence ensures that data is permanently saved after transaction submission.

MySQL: Database Management System vs. Programming LanguageMySQL: Database Management System vs. Programming LanguageApr 16, 2025 am 12:19 AM

MySQL is not only a database management system (DBMS) but also closely related to programming languages. 1) As a DBMS, MySQL is used to store, organize and retrieve data, and optimizing indexes can improve query performance. 2) Combining SQL with programming languages, embedded in Python, using ORM tools such as SQLAlchemy can simplify operations. 3) Performance optimization includes indexing, querying, caching, library and table division and transaction management.

MySQL: Managing Data with SQL CommandsMySQL: Managing Data with SQL CommandsApr 16, 2025 am 12:19 AM

MySQL uses SQL commands to manage data. 1. Basic commands include SELECT, INSERT, UPDATE and DELETE. 2. Advanced usage involves JOIN, subquery and aggregate functions. 3. Common errors include syntax, logic and performance issues. 4. Optimization tips include using indexes, avoiding SELECT* and using LIMIT.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function