How to export data to an excel file in java

Source: Internet
Author: User

Using java to explain how to export data to an excel file:
Download the latest JExcelApi and place jxl. jar in your classpath.
Write a javaBean file and use JExcelApi to dynamically generate an excel file. Here I will write a simple and schematic file. Complex, you may need to query the database or something.
// Test. java
Package com. jarie. test;
Import java. io .*;
Import jxl .*;
Import jxl. write .*;
Import jxl. format .*;
Import java. util .*;
Import java. awt. Color;
Public class Test {
Public static void writeExcel (OutputStream OS) throws Exception {
Jxl. write. WritableWorkbook wwb = Workbook. createWorkbook (OS );
Jxl. write. WritableSheet ws = wwb. createSheet ("TestSheet1", 0 );
Jxl. write. Label labelC = new jxl. write. Label (0, 0, "I love China ");
Ws. addCell (labelC );
Jxl. write. WritableFont wfc = new jxl. write. WritableFont (WritableFont. ARIAL, 20, WritableFont. BOLD, false,
UnderlineStyle. NO_UNDERLINE, jxl. format. Colour. GREEN );
Jxl. write. WritableCellFormat wcfFC = new jxl. write. WritableCellFormat (wfc );
WcfFC. setBackground (jxl. format. Colour. RED );
LabelC = new jxl. write. Label (6, 0, "", wcfFC );
Ws. addCell (labelC );
// Write the Exel Worksheet
Wwb. write ();
// Close the Excel worksheet object
Wwb. close ();
}
// It is best to write such a main method to test whether your class has been written.
Public static void main (String [] args) throws Exception {
File f = new File ("kk.xls ");
F. createNewFile ();
WriteExcel (new FileOutputStream (f ));
}
}

Write a jsp file to use the Test javabean to output the excel file.
// Test_excel.jsp
<Href = "mailto: % @ page"> % @ page import = "com. jarie. test. Test" %>
<%
Response. reset ();
Response. setContentType ("application/vnd. ms-excel ");
Test. writeExcel (response. getOutputStream ());
%>

Then, you can access test_excel.jsp with ie to open the dynamically generated excel file in ie.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.