如何将JSP中将查询结果导出为Excel,其实可以利用jakarta提供的POI接口将查询结果导出到excel。POI接口是jakarta组织的一个子项目,它包括POIFS,HSSF,HWSF,HPSF,HSLF,目前比较成熟的是HSSF,它是一组操作微软的excel文档的API,现在到达3.0版本,已经能够支持将图片插入到excel里面。java 代码
import java.io.*;
- import org.apache.poi.hssf.usermodel.*;
- import org.apache.poi.hssf.util.*;
- import org.apache.poi.hssf.usermodel.contrib.*;
- import javax.imageio.ImageIO;
-
- public class Main {
- public Main() {
- }
-
-
- public static void ex1() {
- try {
- org.apache.poi.hssf.usermodel.HSSFWorkbook wb = new org.apache.poi.
- hssf.usermodel.HSSFWorkbook();
- java.io.FileOutputStream fileOut = new java.io.FileOutputStream(
- "ex1.xls");
- wb.write(fileOut);
- fileOut.close();
- }
- catch (Exception eee) {
- eee.printStackTrace();
- }
- }
-
- public static void ex2() {
- try {
- org.apache.poi.hssf.usermodel.HSSFWorkbook wb = new org.apache.poi.
- hssf.usermodel.HSSFWorkbook();
- org.apache.poi.hssf.usermodel.HSSFSheet sheet1 = wb.createSheet(
- "new sheet");
- org.apache.poi.hssf.usermodel.HSSFSheet sheet2 = wb.createSheet(
- "second sheet");
- java.io.FileOutputStream fileOut = new java.io.FileOutputStream(
- "ex2.xls");
- wb.write(fileOut);
- fileOut.close();
- }
- catch (Exception eee) {
- eee.printStackTrace();
- }
- }
-
- public static void ex3() {
- try {
- org.apache.poi.hssf.usermodel.HSSFWorkbook wb = new org.apache.poi.
- hssf.usermodel.HSSFWorkbook();
- org.apache.poi.hssf.usermodel.HSSFSheet sheet = wb.createSheet(
- "new sheet");
-
- org.apache.poi.hssf.usermodel.HSSFRow row = sheet.createRow( (short)
- 0);
-
- org.apache.poi.hssf.usermodel.HSSFCell cell = row.createCell( (short)
- 0);
- cell.setCellValue(1);
-
- row.createCell( (short) 1).setCellValue(1.2);
- row.createCell( (short) 2).setCellValue("This is a string");
- row.createCell( (short) 3).setCellValue(true);
-
- java.io.FileOutputStream fileOut = new java.io.FileOutputStream(
- "ex3.xls");
- wb.write(fileOut);
- fileOut.close();
- }
- catch (Exception eee) {
- eee.printStackTrace();
- }
- }
-
- public static void ex27() {
- try {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sheet = wb.createSheet("new sheet");
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
- HSSFClientAnchor a = new HSSFClientAnchor(0, 0, 1023, 255,
- (short) 1, 0, (short) 1, 0);
- HSSFSimpleShape shape1 = patriarch.createSimpleShape(a);
- shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE);
- HSSFTextbox textbox1 = patriarch.createTextbox(
- new HSSFClientAnchor(0, 0, 0, 0, (short) 1, 1, (short) 2, 2));
- textbox1.setString(new HSSFRichTextString("This is a test"));
- HSSFFont font = wb.createFont();
- font.setItalic(true);
- font.setUnderline(HSSFFont.U_DOUBLE);
- HSSFRichTextString string = new HSSFRichTextString("Woo!!!");
- string.applyFont(2, 5, font);
- textbox1.setString(string);
-
- HSSFShapeGroup group = patriarch.createGroup(
- new HSSFClientAnchor(0, 0, 900, 200, (short) 2, 2, (short) 2, 2));
-
- shape1 = group.createShape(new HSSFChildAnchor(3, 3, 500, 500));
- shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE);
- ( (HSSFChildAnchor) shape1.getAnchor()).setAnchor( (short) 3, 3,
- 500, 500);
- HSSFSimpleShape shape2 = group.createShape(new HSSFChildAnchor( (short)
- 1, 200, 400, 600));
- shape2.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE);
- group.setCoordinates(10, 10, 20, 20);
- FileOutputStream fileOut = new FileOutputStream("ex27.xls");
- wb.write(fileOut);
- fileOut.close();
- }
- catch (Exception eee) {
- eee.printStackTrace();
- }
- }
-
- public static void ex28() {
- try {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sheet1 = wb.createSheet("new sheet");
- sheet1.groupRow(5, 14);
- sheet1.groupRow(7, 14);
- sheet1.groupRow(16, 19);
- sheet1.groupColumn( (short) 4, (short) 7);
- sheet1.groupColumn( (short) 9, (short) 12);
- sheet1.groupColumn( (short) 10, (short) 11);
- FileOutputStream fileOut = new FileOutputStream("ex28.xls");
- wb.write(fileOut);
- fileOut.close();
- }
- catch (Exception eee) {
- eee.printStackTrace();
- }
- }
-
- public static void ex29() {
- try {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sheet = wb.createSheet("new sheet");
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
- HSSFClientAnchor a = new HSSFClientAnchor(0, 0, 1023, 255,
- (short) 1, 0, (short) 1, 0);
- HSSFShapeGroup group = patriarch.createGroup(a);
- group.setCoordinates(0, 0, 80 * 4, 12 * 23);
- float verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet) /
- (float) Math.abs(group.getY2() - group.getY1());
- EscherGraphics g = new EscherGraphics(group, wb,
- java.awt.Color.black,
- verticalPointsPerPixel);
- EscherGraphics2d g2d = new EscherGraphics2d(g);
-
- FileOutputStream fileOut = new FileOutputStream("ex29.xls");
- wb.write(fileOut);
- fileOut.close();
- }
- catch (Exception eee) {
- eee.printStackTrace();
- }
- }
-
- public static void ex30() {
- try {
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sheet = wb.createSheet("new sheet");
- HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
- HSSFClientAnchor anchor;
- anchor = new HSSFClientAnchor(0, 0, 0, 255, (short) 2, 2, (short) 4,
- 7);
- anchor.setAnchorType(2);
- patriarch.createPicture(anchor,
- loadPicture(
- "1.jpg",
- wb));
- FileOutputStream fileOut = new FileOutputStream("ex30.xls");
- wb.write(fileOut);
- fileOut.close();
- }
- catch (Exception eee) {
- eee.printStackTrace();
- }
- }
- private static int loadPicture(String filePath, HSSFWorkbook wb) {
- int result = 0;
- try {
- ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
- java.awt.image.BufferedImage bufferImg = ImageIO.read(new File(
- filePath));
- ImageIO.write(bufferImg,"jpg",byteArrayOut);
- result = wb.addPicture(byteArrayOut.toByteArray(),HSSFWorkbook.PICTURE_TYPE_JPEG);
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- return result;
- }
- }
java中利用poi创建和读取excel文件
前面做了个项目,要求利用java动态读取数据库中的数据到excel文件供客户下载,同时把客户上传的excel文件读入到数据库中。
查了些资料,最后用的是poi-2.5.1-final-20040804.jar,完全可以满足要求。下面以一段程序为例,说明poi的用法:
/*
* Created on 2006-8-4
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.crm.web.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*这一块导入相关类*/
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/*这一块导入相关类*/
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.crm.dao.CompanyAccountsDAO;
import com.crm.dao.CustomerDAO;
import com.crm.dao.CustomerLinkmanDAO;
import com.crm.dao.MarketOpportunityDAO;
import com.crm.dao.MembersDAO;
import com.crm.dao.OrderDAO;
import com.crm.dao.QuotePriceDAO;
import com.crm.dao.ScheduleDAO;
import com.crm.dto.CustomerDTO;
import com.crm.web.form.CustomerForm;
/**
* @author new
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
public class CustomerAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
CustomerForm customerForm = (CustomerForm) form;
if (customerForm.getOperType() != null
&& customerForm.getOperType().equals("exportCustomer")) {
/* 导出客户 */
String companyID = (String) request.getSession().getValue(
"companyID");
CustomerDAO customerDAO = new CustomerDAO();
String accountsType = (String) request.getSession().getValue(
"accountsType");
String accounts = (String) request.getSession()
.getValue("accounts");
String department = (String) request.getSession().getValue(
"department");
Vector customerList = new Vector();
if (accountsType.equals("1")) {
customerList = ((Vector) customerDAO.findEmployeeCustomer(
Integer.parseInt(accounts), "0"));
} else if (accountsType.equals("2")) {
customerList = ((Vector) customerDAO.findDepartmentCustomer(
Integer.parseInt(companyID), Integer
.parseInt(department), "0"));
} else if (accountsType.equals("3")) {
customerList = ((Vector) customerDAO.findCompanyCustomer(
Integer.parseInt(companyID), "0"));
}
try {
// 创建新的Excel 工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
// 在Excel工作簿中建一工作表,其名为缺省值
// 如要新建一名为"效益指标"的工作表,其语句为:
// HSSFSheet sheet = workbook.createSheet("效益指标");
/*或者不提供参数,创建一个无名工作表*/
HSSFSheet sheet = workbook.createSheet();
// 在索引0的位置创建行(最顶端的行)
HSSFRow row = sheet.createRow((short) 0);
//在索引0的位置创建单元格(左上端)
HSSFCell cell;
//= row.createCell((short) 0);
// 定义单元格为字符串类型
//cell.setCellType(HSSFCell.CELL_TYPE_STRING);
//设置cell编码解决中文高位字节截断
//cell.setEncoding(HSSFCell.ENCODING_UTF_16);
// 在单元格中输入一些内容
int i = 0;
cell = row.createCell((short) i++);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("客户信息ID(customerInformationID)");
cell = row.createCell((short) i++);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("公司名称(我的公司)companyName");
cell = row.createCell((short) i++);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("客户名称customerName");
cell = row.createCell((short) i++);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("客户简称nameForShort");
cell = row.createCell((short) i++);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("公司地址companyAddress");
// 下面是不断从数据库中读数据到sheet中
for (int j = 0; j < customerList.size(); j++) {
CustomerDTO customerDTO = (CustomerDTO) customerList.get(j);
i = 0;
row = sheet.createRow((short) j + 1);
cell = row.createCell((short) i++);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(customerDTO.getCustomerInformationID());
cell = row.createCell((short) i++);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(customerDTO.getCompanyName());
cell = row.createCell((short) i++);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(customerDTO.getCustomerName());
}
// 新建一输出文件流
String outputFile = request.getRealPath("/")
+ "customer\\excel\\" + accounts + ".xls";
/* 如果文件存在则删除它 */
File oldFile = new File(outputFile);
if (oldFile.exists()) {
oldFile.delete();
}
FileOutputStream fOut = new FileOutputStream(outputFile);
// 把相应的Excel 工作簿存盘
workbook.write(fOut);
fOut.flush();
// 操作结束,关闭文件
fOut.close();
customerForm.setExcelFilePath(outputFile);
System.out.println("文件生成...");
} catch (Exception e) {
System.out.println("已运行 xlCreate() : " + e);
}
return mapping.findForward("exportCustomerSuccess");
} else if (customerForm.getOperType() != null
&& customerForm.getOperType().equals("importCustomer")) {
/*下面是从excel中读取数据的例子*/
CustomerDAO customerDAO = new CustomerDAO();
String accounts = (String) request.getSession()
.getValue("accounts");
String fileToBeRead = request.getRealPath("/")
+ "customer\\excel\\upload_" + accounts + ".xls";
try {
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(
fileToBeRead));
HSSFSheet sheet = workbook.getSheetAt(0);
/* 读取文件中的信息,并把数据存入数据库 */
for (int j = 1;; j++) {
HSSFRow row = sheet.getRow(j);
if (row != null) {
CustomerDTO customerDTO = new CustomerDTO();
HSSFCell cell;
int i = 0;
/* 跳过第一列的customerInformationID */
i++;
cell = row.getCell((short) i++);
customerDTO.setCompanyName(cell.getStringCellValue());
cell = row.getCell((short) i++);
customerDTO.setCustomerName(cell.getStringCellValue());
cell = row.getCell((short) i++);
customerDTO.setNameForShort(cell.getStringCellValue());
cell = row.getCell((short) i++);
customerDTO
.setCompanyAddress(cell.getStringCellValue());
cell = row.getCell((short) i++);
customerDTO.setCountry(cell.getStringCellValue());
cell = row.getCell((short) i++);
customerDTO.setProvince(cell.getStringCellValue());
cell = row.getCell((short) i++);
customerDTO.setCity(cell.getStringCellValue());
cell = row.getCell((short) i++);
customerDTO.setPostalcode(cell.getStringCellValue());
cell = row.getCell((short) i++);
customerDTO.setCompanyHomePage(cell
.getStringCellValue());
customerDAO.insertCustomer(customerDTO);
} else {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
/* 设置返回目标 */
String companyID = (String) request.getSession().getValue(
"companyID");
String accountsType = (String) request.getSession().getValue(
"accountsType");
String department = (String) request.getSession().getValue(
"department");
CompanyAccountsDAO companyAccountsDAO = new CompanyAccountsDAO();
if (accountsType.equals("1")) {
customerForm.setCustomerList((Vector) customerDAO
.findEmployeeCustomer(Integer.parseInt(accounts), "0"));
} else if (accountsType.equals("2")) {
customerForm.setCustomerList((Vector) customerDAO
.findDepartmentCustomer(Integer.parseInt(companyID),
Integer.parseInt(department), "0"));
customerForm.setAccountsList((Vector) companyAccountsDAO
.findDepartmentAccounts(companyID, department));
} else if (accountsType.equals("3")) {
customerForm.setCustomerList((Vector) customerDAO
.findCompanyCustomer(Integer.parseInt(companyID), "0"));
customerForm.setAccountsList((Vector) companyAccountsDAO
.findAllAccounts(companyID));
}
return mapping.findForward("allCustomer");
}
return mapping.findForward("");
}
}
posted on 2007-08-09 12:26
Sun River 阅读(1709)
评论(0) 编辑 收藏 所属分类:
Struts