struts 文件下载——导出Excle/导出PDF

######导出Excle########

public InputStream getTableTransaction() throws FileNotFoundException {
  Date datenow=new Date();
  SimpleDateFormat  dateFormatNow=new SimpleDateFormat ("yyyy-M-d-HH-mm-ss");
  String dateNow=dateFormatNow.format(datenow);
  String path=ServletActionContext.getServletContext().getRealPath("/DatExport").replace("/", "\\")+"\\"+dateNow+".csv";   //路径
  File f=new File(path);
  HttpSession session = ServletActionContext.getRequest().getSession();
  saveTransactionList=(List<invoice>)session.getAttribute("list");
  try
  {
   if(f.createNewFile())
   {
    String Contxt=new String();
    String line="Invoice Number, Invoice Date,Invoice Status,Client,Start Date,End Date,Due Date,Currency,Invoice Amount,PST," +    //表头
      "GST,QST,HST,Discount Amounts"+"\r\n";
    Contxt=line;
    if(saveTransactionList!=null)
    {
     for(int i=0;i<saveTransactionList.size();i++)
     {
         invoice st=saveTransactionList.get(i);
      line=st.getInvoicenumber()+","+st.getInvoicedate()+","+st.getInvoicestatus()+","+st.getClientname()+","+st.getStartdate()+","+st.getEnddate()   //内容
        +","+st.getDuedate()+","+st.getCurrency()+","+st.getInvoiceamount()+","+st.getPst()+","+st.getGst()+","+st.getQst()
        +","+st.getHst()+","+st.getDisc_amount()+"\r\n";
      Contxt+=line;
     }
    }
    BufferedWriter output = new BufferedWriter(new FileWriter(f));
       output.write(Contxt);
       output.close();
   }
  }catch (IOException e)
  {
   e.printStackTrace();
  }
  tableTransaction=new java.io.FileInputStream(path);
  return tableTransaction;
 }

 

struts 配置

<action name="searchInvoiceAction*" class="com.hruisoft.www.action.Invoice"
   method="{1}">
   <result name="success">/invoice.jsp</result>
   <result name="fail">/login.jsp</result>
   <result name="ExportToCsv" type="stream">
    <param name="contentType">text/plain</param>
    <param name="inputName">tableTransaction</param>
    <param name="contentDisposition">attachment;filename="report.csv"</param>
    <param name="bufferSize">4096</param>
   </result>
  </action>

 

 ######导出PDF########

public InputStream getPdfTable() throws FileNotFoundException {
  Date datenow=new Date();
  SimpleDateFormat  dateFormatNow=new SimpleDateFormat ("yyyy-M-d-HH-mm-ss");
  String dateNow=dateFormatNow.format(datenow);
  String path=ServletActionContext.getServletContext().getRealPath("/DatExport").replace("/", "\\")+"\\"+dateNow+".pdf";
  try
  {
   HttpSession session = ServletActionContext.getRequest().getSession();  
   String reportType="";
   if(session.getAttribute("reportType")!=null)
    reportType=(String)session.getAttribute("reportType");
   Document document = new Document(PageSize.A4.rotate());   
   PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(path));
   HeaderFooter footer = new HeaderFooter(new Phrase("Page ",new Font(Font.HELVETICA, 6)), true);
   footer.setBorder(Rectangle.NO_BORDER);
   footer.setAlignment(0);
   document.setFooter(footer);
   document.open();
   PdfPTable table = new PdfPTable(14); //设置列数
   PdfPCell pcell1 = new PdfPCell(new Phrase("Card #", new Font(Font.TIMES_ROMAN, 6, Font.BOLD,Color.BLACK)));
   pcell1.setBackgroundColor(Color.LIGHT_GRAY);
   pcell1.setHorizontalAlignment(2);
   PdfPCell pcell2 = new PdfPCell(new Phrase("Unit #", new Font(Font.TIMES_ROMAN, 6, Font.BOLD, Color.BLACK)));
   pcell2.setBackgroundColor(Color.LIGHT_GRAY);
   pcell2.setHorizontalAlignment(2);
   PdfPCell pcell3 = new PdfPCell(new Phrase("Driver Name", new Font(Font.TIMES_ROMAN, 6, Font.BOLD, Color.BLACK)));
   pcell3.setBackgroundColor(Color.LIGHT_GRAY);
   pcell3.setHorizontalAlignment(2);
   PdfPCell pcell4 = new PdfPCell(new Phrase("DATE", new Font(Font.TIMES_ROMAN, 6, Font.BOLD, Color.BLACK)));
   pcell4.setBackgroundColor(Color.LIGHT_GRAY);
   pcell4.setHorizontalAlignment(2);
   PdfPCell pcell5 = new PdfPCell(new Phrase("TIME", new Font(Font.TIMES_ROMAN, 6, Font.BOLD, Color.BLACK)));
   pcell5.setBackgroundColor(Color.LIGHT_GRAY);
   pcell5.setHorizontalAlignment(2);
   PdfPCell pcell6 = new PdfPCell(new Phrase("Site Number", new Font(Font.TIMES_ROMAN, 6, Font.BOLD, Color.BLACK)));
   pcell6.setBackgroundColor(Color.LIGHT_GRAY);
   pcell6.setHorizontalAlignment(2);
   PdfPCell pcell7 = new PdfPCell(new Phrase("Site Name", new Font(Font.TIMES_ROMAN, 6, Font.BOLD, Color.BLACK)));
   pcell7.setBackgroundColor(Color.LIGHT_GRAY);
   pcell7.setHorizontalAlignment(2);
   PdfPCell pcell9 = new PdfPCell(new Phrase("Province/State", new Font(Font.TIMES_ROMAN, 6, Font.BOLD, Color.BLACK)));
   pcell9.setBackgroundColor(Color.LIGHT_GRAY);
   pcell9.setHorizontalAlignment(2);
   PdfPCell pcell10 = new PdfPCell(new Phrase("Tractor Fuel", new Font(Font.TIMES_ROMAN, 6, Font.BOLD, Color.BLACK)));
   pcell10.setBackgroundColor(Color.LIGHT_GRAY);
   pcell10.setHorizontalAlignment(2);
   PdfPCell pcell11 = new PdfPCell(new Phrase("Reefer Fuel", new Font(Font.TIMES_ROMAN, 6, Font.BOLD, Color.BLACK)));
   pcell11.setBackgroundColor(Color.LIGHT_GRAY);
   pcell11.setHorizontalAlignment(2);
   PdfPCell pcell12 = new PdfPCell(new Phrase("Fuel QTY", new Font(Font.TIMES_ROMAN, 6, Font.BOLD, Color.BLACK)));
   pcell12.setBackgroundColor(Color.LIGHT_GRAY);
   pcell12.setHorizontalAlignment(2);
   PdfPCell pcell13 = new PdfPCell(new Phrase("Litre or Gallon", new Font(Font.TIMES_ROMAN, 6, Font.BOLD, Color.BLACK)));
   pcell13.setBackgroundColor(Color.LIGHT_GRAY);
   pcell13.setHorizontalAlignment(2);
    PdfPCell pcellPFT = new PdfPCell(new Phrase("Previous Odometer ", new Font(Font.TIMES_ROMAN, 6, Font.BOLD, Color.BLACK)));
   pcellPFT.setBackgroundColor(Color.LIGHT_GRAY);
   pcellPFT.setHorizontalAlignment(2);
   PdfPCell pcellHET = new PdfPCell(new Phrase("Odometer", new Font(Font.TIMES_ROMAN, 6, Font.BOLD, Color.BLACK)));
   pcellHET.setBackgroundColor(Color.LIGHT_GRAY);
   pcellHET.setHorizontalAlignment(2);
   table.addCell(pcell1);
   table.addCell(pcell2);
   table.addCell(pcell3);
   table.addCell(pcell4);
   table.addCell(pcell5);
   table.addCell(pcell6);
   table.addCell(pcell7);
   table.addCell(pcell9);
   table.addCell(pcell10);
   table.addCell(pcell11);
   table.addCell(pcell12);
   table.addCell(pcell13);
   table.addCell(pcellPFT);
   table.addCell(pcellHET);
   saveReportList=(List<report>)session.getAttribute("list");
   if(saveReportList!=null)
   {
    Font pdfCellFont=new Font(Font.TIMES_ROMAN, 5,Font.NORMAL,Color.BLACK); //All cell font format
   for(int i=0;i<saveReportList.size();i++)
   {
    report st=saveReportList.get(i);
    table.addCell(new Phrase(st.getCardnumber(),pdfCellFont));//, font));
    table.addCell(new Phrase(st.getUnitnumber(),pdfCellFont));//, font));
    table.addCell(new Phrase(st.getDrivername(),pdfCellFont));//, font));
    table.addCell(new Phrase(st.getDate(),pdfCellFont));//, font));
    table.addCell(new Phrase(st.getTime(),pdfCellFont));//, font));
    table.addCell(new Phrase(st.getSitenumber(),pdfCellFont));//, font));
    table.addCell(new Phrase(st.getSitename(),pdfCellFont));//, font));
    table.addCell(new Phrase(st.getState(),pdfCellFont));//, font));
    table.addCell(new Phrase(st.getTractorfuel(),pdfCellFont));//, font));
    table.addCell(new Phrase(st.getReferfuel(),pdfCellFont));//, font));
    table.addCell(new Phrase(st.getFuelqty(),pdfCellFont));//, font));
    table.addCell(new Phrase(st.getUom(),pdfCellFont));//, font));
    table.addCell(new Phrase(st.getPreviousOdometer(),pdfCellFont));//, font));
    table.addCell(new Phrase(st.getOdometer(),pdfCellFont));//, font));
      }
   }
   document.add(table);
   document.close();
   writer.close();
  }
  catch(FileNotFoundException e)
  {
   e.printStackTrace();
  } catch (DocumentException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }  
  pdfTable=new java.io.FileInputStream(path);
  return pdfTable;
 }

 struts 配置与上面类似

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的JSP页面,用于从数据库中检索数据并将其导出为Excel文件: ```jsp <%@ page import="java.io.*,java.sql.*,org.apache.poi.ss.usermodel.*" %> <%@ page contentType="application/vnd.ms-excel" language="java" %> <%@ page import="javax.servlet.http.*,javax.servlet.*" %> <% // 设置响应头,提示浏览器下载文件 response.setHeader("Content-Disposition", "attachment; filename=myfile.xlsx"); // 创建工作簿和工作表对象 Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("数据"); // 创建标题行并设置单元格样式 Row headerRow = sheet.createRow(0); CellStyle headerCellStyle = workbook.createCellStyle(); headerCellStyle.setFillForegroundColor(IndexedColors.BLUE_GREY.getIndex()); headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); headerCellStyle.setAlignment(HorizontalAlignment.CENTER); Font headerFont = workbook.createFont(); headerFont.setColor(IndexedColors.WHITE.getIndex()); headerFont.setBold(true); headerCellStyle.setFont(headerFont); // 添加标题行的单元格 Cell headerCell1 = headerRow.createCell(0); headerCell1.setCellValue("ID"); headerCell1.setCellStyle(headerCellStyle); Cell headerCell2 = headerRow.createCell(1); headerCell2.setCellValue("名称"); headerCell2.setCellStyle(headerCellStyle); Cell headerCell3 = headerRow.createCell(2); headerCell3.setCellValue("价格"); headerCell3.setCellStyle(headerCellStyle); // 从数据库中检索数据并将其填充到工作表中 try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password"); PreparedStatement ps = con.prepareStatement("SELECT * FROM products"); ResultSet rs = ps.executeQuery(); int rowNumber = 1; while (rs.next()) { Row row = sheet.createRow(rowNumber++); row.createCell(0).setCellValue(rs.getInt("id")); row.createCell(1).setCellValue(rs.getString("name")); row.createCell(2).setCellValue(rs.getDouble("price")); } con.close(); } catch (Exception e) { out.println(e); } // 将工作簿写入输出流,并关闭工作簿 workbook.write(out); workbook.close(); %> ``` 该页面从数据库中检索数据,并将其填充到Excel文件的工作表中。我们使用Apache POI库来创建工作簿和工作表,并将数据填充到单元格中。在上面的示例中,我们使用MySQL数据库,但您可以将其替换为任何其他数据库,只需更改JDBC连接字符串、用户名和密码即可。在JSP页面的顶部,我们设置了响应头,以便浏览器将文件下载到本地计算机。我们还将页面的`contentType`设置为`application/vnd.ms-excel`,以便浏览器知道我们正在发送Excel文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值