java操作xls与pdf文件 struts下载实例

jxl是一个java操作excel的工具, 在开源世界中,有两套比较有影响的API可供使用,一个是POI,一个是jExcelAPI。其中功能相对POI比较弱一点。但jExcelAPI对中文支持非常好,API是纯Java的, 并不依赖Windows系统,即使运行在Linux下,它同样能够正确的处理Excel文件。 另外需要说明的是,这套API对图形和图表的支持很有限,而且仅仅识别PNG格式。

此代码在工厂框架中应用有些地方不是用详细

jsp中的代码



<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/commons/taglibs.jsp"%>

<html>
	<head>
		<title></title>

		<link rel="stylesheet" type="text/css" href="../styles/default.css" />
		<link rel="stylesheet" type="text/css" href="../styles/main.css" />
		<%@ include file="/commons/meta.jsp"%>

		<script type="text/javascript">
   function onloadXls(){
   alert("start onload...");
   document.URL="xls.do?action=onloadXls";   
   }
    function onloadPdf(){
   alert("start onload...");
   document.URL="xls.do?action=onloadPdf";   
   }
 </script>

	</head>

	<body>
		<div class="pageTitle">
			xls下载
		</div>
		<div class="list">
			<div class="listTopOperation">
				<div class="select">
					<div id="_list_IUD" class="IUD">
						<button onclick="onloadXls()">
							下载xls
						</button>
						<button onclick="onloadPdf()">
							下载pdf
						</button>
					</div>
				</div>
				<table id="mytable" border="0" cellspacing="1" cellpadding="0" width="100%">
				<thead>
					<tr>
						<th width="30px;">
							选择
						</th>
						<th>
							编号
						</th>
						<th>
							名称
						</th>
						<th>
							价格
						</th>
						<th>
							备注
						</th>
					</tr>
				</thead>
				<tbody id="_list_Tbody">
					<c:forEach var="c" items="${requestScope.com}">
						<tr selected="false" keyName="num" keyValue="${c.id}">
							<td>
								<input name="checkedlist" type="radio" value="${c.id}">
							</td>
							<td>
								${c.id}
							</td>
							<td>
								${c.productName }
							</td>
							<td>
								${c.productPrice }
							</td>
							<td>
								${c.productRemark }
							</td>
						</tr>
					</c:forEach>
				</tbody>
			</table>
			<div>
			</div>
	</body>
</html>











struts中的代码


package com.newer.business.xls.web.action;

import java.awt.Color;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.format.UnderlineStyle;
import jxl.write.Colour;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.lowagie.text.Cell;
import com.lowagie.text.Chapter;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Section;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;
import com.newer.business.commodity.manager.CommodityManager;
import com.newer.business.pojo.Commodity;
import com.newer.core.web.StrutsAction;

public class XlsAction extends StrutsAction {
	private CommodityManager com;
	
	public void setCom(CommodityManager com) {
		this.com = com;
	}
	//进入主页显示所有商品信息
	public ActionForward xlsIndex(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
        request.setAttribute("com",com.getAll());
		return mapping.findForward("index");
	}

/*****************************************xls下载————开始***************************************************/	
	
	// 开始下载xls
	public ActionForward onloadXls(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
System.out.println("start onload................xls");
            //调用弹出框
            response(request,response,getXlsFile(request));	
		return null;
	}
	
	 // 获得xls文件向xls文件中添加数据
	  @SuppressWarnings("deprecation")
	private File getXlsFile(HttpServletRequest request) {
		//xls文件存放路径 项目中的pdfOrxls文件夹中
		String pathName=request.getRealPath("/")+"pdfOrxls/文件xls.xls";
		
		File file = new File(pathName);
		try {
			if (!file.exists()) {
				file.createNewFile();
			}
			// 打开文件
			WritableWorkbook book = Workbook.createWorkbook(file);
			// 生成名为“第一页”的工作表,参数0表示这是第一页
			WritableSheet sheet = book.createSheet(" 第一页", 0);
			 //设置大标题样式
			 WritableFont title =    
				 new  WritableFont(WritableFont.TIMES, 16 ,WritableFont.BOLD,false, UnderlineStyle.NO_UNDERLINE,   
			                Colour.RED); 
				WritableCellFormat format1 = new  WritableCellFormat(title);
				 //把水平对齐方式指定为居中  
				format1.setAlignment(jxl.format.Alignment.CENTRE);  	
		//合并第一列第一行到第三列第一行的所有单元格 	
		 sheet.mergeCells(0,0,3,0);
		 sheet.addCell(new Label(0,0,"商品信息",format1));
		 //设置小标题样式
		 WritableFont font=    
			 new  WritableFont(WritableFont.TIMES, 10 ,WritableFont.BOLD,false, UnderlineStyle.NO_UNDERLINE,   
		                Colour.BLACK);
		format1 = new  WritableCellFormat(font);
		format1.setBackground(Colour.CORAL);
		 // 把垂直对齐方式指定为居中    
		 format1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
		 //给xls文件添加标题
		 sheet.addCell(new Label(0,1,"商品ID",format1));
		 sheet.addCell(new Label(1,1,"商品名称",format1));
		 sheet.addCell(new Label(2,1,"商品价格",format1));
		 sheet.addCell(new Label(3,1,"商品备注",format1));
		 //设置内容样式
		 WritableFont context=    
			 new  WritableFont(WritableFont.TIMES, 10 ,WritableFont.NO_BOLD,false, UnderlineStyle.NO_UNDERLINE,   
		                Colour.GRAY_25);
		format1 = new  WritableCellFormat(context);
		 // 把垂直对齐方式指定为居中    
		 format1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
		//获得商品信息集合
		 List<Commodity> list=com.getAll();
		 //给xls文件添加内容
		 for(int i=0;i<list.size();i++){
		     Commodity c=list.get(i);
		     jxl.write.Number id = new jxl.write.Number(0,i+2,c.getId(),format1);
			 sheet.addCell(id);
			 Label name = new Label(1, i+2,c.getProductName(),format1);
			 sheet.addCell(name);
			 jxl.write.Number price = new jxl.write.Number(2,i+2,c.getProductPrice(),format1);
			 sheet.addCell(price);
			 Label remark= new Label(3, i+2,c.getProductRemark(),format1);
			 sheet.addCell(remark);
		 }
			// 写入数据并关闭文件
			book.write();
			book.close();

		} catch (Exception e) {
			System.out.println(e);
		}
		return file;
	}
/*****************************************xls下载————结束***************************************************/
	
	
/*****************************************pdf下载————开始***************************************************/	
	
	// 开始下载pdf
	public ActionForward onloadPdf(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
System.out.println("start onload................pdf");
		//调用弹出框
		response(request,response,getPdfFile(request));	
			return null;
	}
	
  // 获得pdf文件向pdf文件中添加数据	
  @SuppressWarnings("deprecation")
private File  getPdfFile(HttpServletRequest request){
	  
	  // 创建一个Document对象
	    Document document = new Document();
        File file=null;
	    try 
	    {      
	    	//pdf文件存放路径 项目中的pdfOrxls文件夹中
			String pathName=request.getRealPath("/")+"pdfOrxls/文件pdf.pdf";
	    	 file=new File(pathName);
		  // 生成名为文件pdf.pdf 的文档	
	      PdfWriter.getInstance(document, new FileOutputStream(pathName));
	      // 添加PDF文档的一些信息
	      document.addTitle("Hello World example");
	      document.addAuthor("Bruno Lowagie");
	      document.addSubject("This example explains how to add metadata.");
	      document.addKeywords("iText, Hello World, step 3, metadata");
	      document.addCreator("My program using iText");
	      // 打开文档,将要写入内容
	      document.open();
	      //显示中文必须设置中文字体
	      BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
	      Font  toptitle = new Font(bfChinese, 16, Font.BOLD, Color.red); 
	      Font  title = new Font(bfChinese, 10, Font.BOLD, Color.ORANGE); 
	      Font  font = new Font(bfChinese, 8, Font.COURIER, Color.GRAY);
	      //设置段落标题并设置字体
	      Paragraph chapterTitle = new Paragraph("商品信息",toptitle);
	      //创建了一个章节的对象,标题为"Chapter 1"
	      Chapter chapter1 = new Chapter(chapterTitle,1);
	      //设置为0,则在标题前面没有编号.反之...
	      chapter1.setNumberDepth(0);
	      //创建章节下的子章节.
	      Paragraph sectionTitle = new Paragraph("Version No 1.1", toptitle);
	      //添加对象,属于chapter1。
	      Section section1 = chapter1.addSection(sectionTitle);
	      //写文本内容
	      Paragraph text = new Paragraph("创建人:admin",title);
	      section1.add(text);
	      text = new Paragraph("创建时间:"+new Date(),title);
	      section1.add(text);
	      //创建表格对象
	      Table table = new Table(4);
	      //设置表格边框颜色
	      table.setBorderColor(new Color(220, 255, 100));
	      //边距
	      table.setPadding(1);
	      //间距
	      table.setSpacing(1);
	      table.setBorderWidth(1);
	      //整个表居中
	      table.setAlignment(1);
	      //单元格对象
	      Cell cell = null;
	      
	      //添加表头信息
	      cell= new Cell (new Paragraph ("商品信息",toptitle)); 
	       cell.setHeader(true);
	       cell.setColspan(4);
	       //内容居中对齐
	       cell.setHorizontalAlignment(Element.ALIGN_CENTER);
	       table.addCell(cell);
	       table.endHeaders();
	       //添加表标题
	       cell= new Cell (new Paragraph("商品ID",title));
	       cell.setBackgroundColor(Color.GRAY);
	       cell.setHorizontalAlignment(Element.ALIGN_CENTER);
	       table.addCell(cell);
	       cell= new Cell (new Paragraph("商品名称",title));
	       cell.setBackgroundColor(Color.GRAY);
	       cell.setHorizontalAlignment(Element.ALIGN_CENTER);
	       table.addCell(cell);
	       cell= new Cell (new Paragraph("商品价格",title));
	       cell.setBackgroundColor(Color.GRAY);
	       cell.setHorizontalAlignment(Element.ALIGN_CENTER);
	       table.addCell(cell);
	       cell= new Cell (new Paragraph("商品备注",title));
	       cell.setBackgroundColor(Color.GRAY);
	       cell.setHorizontalAlignment(Element.ALIGN_CENTER);
	       table.addCell(cell);
	      //添加表的内容
	         //获得商品信息集合
			 List<Commodity> list=com.getAll();
			 //给pdf文件添加内容
			 for(int i=0;i<list.size();i++){
			     Commodity c=list.get(i);
	             table.addCell(new Paragraph(c.getId()+"",font));
	             table.addCell(new Paragraph(c.getProductName(),font));
	             table.addCell(new Paragraph(c.getProductPrice()+"",font));
	             table.addCell(new Paragraph(c.getProductRemark(),font));
	      }
	      //将表格对象添加到对象中
	      section1.add(table); 

	      document.add(section1);
	
	    } 
	    catch (Exception de) 
	    { 
	      System.err.println(de.getMessage());
	    }
        finally{
	    // 关闭打开的文档
	   document.close();
        }
	return file;    
  }
/*****************************************pdf下载————结束***************************************************/
  
/***************************************下载弹出框—————开始***********************************************/
  //弹出对话框下载
	private void response(HttpServletRequest request, HttpServletResponse response,File file){
		  BufferedInputStream bis = null;
			BufferedOutputStream bos = null;
			OutputStream fos = null;
			InputStream fis = null;
		try{
		    //获得处理过的xls文件或pdf文件 file
			File uploadFile =file;
			fis = new FileInputStream(uploadFile);
			bis = new BufferedInputStream(fis);
			fos = response.getOutputStream();
			bos = new BufferedOutputStream(fos);
			// 这个就就是弹出下载对话框的关键代码
			response.setHeader("Content-disposition", "attachment;filename="
					+ URLEncoder.encode(uploadFile.getName(), "utf-8"));
			int bytesRead = 0;
			// 这个地方的同上传的一样。我就不多说了,都是用输入流进行先读,然后用输出流去写,唯一不同的是我用的是缓冲输入输出流
			byte[] buffer = new byte[8192];
			while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
				bos.write(buffer, 0, bytesRead);
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		finally{
			try{
			bos.flush();
			fis.close();
			bis.close();
			fos.close();
			bos.close();
			}catch(Exception e){
				//e.printStackTrace();
	System.out.println("下载弹出框出错了...................");			
			}
		}
	  }
/***************************************下载弹出框—————结束***********************************************/	
  
}

你可能感兴趣的:(java,C++,struts,Excel,C#)