1. 程式人生 > >教你學會下載圖片,文檔,excel導入導出

教你學會下載圖片,文檔,excel導入導出

auto sub als size style input 第一個 works 編號

Q1:下載圖片,文檔

--1:Fileio.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <p>
        <a href="Download?filename=images/猴哥.jpg">下載猴哥0</a><br /> <a
            href="Download?filename=images/pic(10).jpg">下載圖片1</a><br /> <a
            href
="Download?filename=images/pic(11).jpg">下載圖片2</a><br /> <a href="Download?filename=images/pic(12).jpg">下載圖片3</a> </p> <p> <a href="Download?filename=LICENSE.txt">下載文本</a> </p> </body> </html>

-2:servlet(Download)

package com.action;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; @WebServlet("/Download") public class Download extends HttpServlet { private static final long serialVersionUID = 1L; public Download() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filename = request.getParameter("filename"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); //獲得要下載的文件路徑 String path=getServletContext().getRealPath(filename); System.out.println(path); //獲得文件名 //H:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\AjaxResult\images\12.jpg String name=path.substring(path.lastIndexOf("\\")+1); //轉碼 name=URLEncoder.encode(name,"utf-8"); //修改http頭部,設置輸出為附件 response.setHeader("Content-Disposition", "attachment;filename="+name); //輸入流,獲得文件的字節流 InputStream is=new FileInputStream(path); byte[] bytes=new byte[is.available()]; is.read(bytes); //將字節流寫入response中 response.getOutputStream().write(bytes); is.close(); response.flushBuffer(); response.getOutputStream().flush(); } }

技術分享圖片

--點擊下載時

技術分享圖片

提示:本文的最後會有java編譯器圖片附上

Q2:Excel導出的第一種方式,也是比較簡單的一種方式

1.html用上面的就好,只是加了一點代碼

<P>

        <a href="DownloadXLS">導出xls</a>
    </P>

2:servlet(DownloadXLS)--此方法用於不連接數據庫操作

package com.action;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/DownloadXLS")
public class DownloadXLS extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public DownloadXLS() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String filename = request.getParameter("filename");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        // 寫入bom頭
        byte[] uft8bom={(byte)0xef,(byte)0xbb,(byte)0xbf};
    
        String name=URLEncoder.encode("月度收入報表.csv","utf-8"); 
        
        //修改http頭部,設置輸出為附件
        response.setHeader("Content-Disposition", "attachment;filename="+name);
        
        String result="日期,收入\r\n";
        
        for (int i = 1; i <=10; i++) {
            result+="2018-06-"+i+","+(i*10)+"萬\r\n";
        }
        result=new String(result.getBytes(),"utf-8");
        //將字節流寫入response中
        response.getOutputStream().write(uft8bom);  //寫入頭部解決亂碼問題
        response.getOutputStream().write(result.getBytes("utf-8"));
        response.flushBuffer();
        response.getOutputStream().flush();
    }

}

3:servlet(DownloadXLS)--此方法用於連接數據庫操作

package com.action;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bos.Menuboimpl;
import com.vos.Menu;



@WebServlet("/DownloadXLS")
public class DownloadXLS extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public DownloadXLS() {
        super();
    }
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         String filename = request.getParameter("filename");
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel");//此處我是用了火狐瀏覽器,這句話非常重要,下面會有介紹
            // 寫入bom頭
            byte[] uft8bom={(byte)0xef,(byte)0xbb,(byte)0xbf};
        
            String name=URLEncoder.encode("月度收入報表.csv","utf-8"); 
            
            //修改http頭部,設置輸出為附件
            response.setHeader("Content-Disposition", "attachment;filename="+name);
            
            String result="編號,類型,名稱,價格,狀態,折扣,日期\r\n";
            Menuboimpl mi=new Menuboimpl();
            int mmtid=Integer.parseInt(request.getParameter("mmtid"));
            System.out.println(mmtid);
            //int mmtid=1;
            List<Menu> list=null;
            if(mmtid==0) {
                list=mi.getMenuAllListAll();
            }else {
                 list=mi.getMenuAllList(mmtid);
            }
            for(Menu item:list) {
                 result+=item.getMid()+","+item.getMmtid()+","+item.getMname()+","+item.getMprice()+","+
            item.getStatus()+","+item.getMdiscount()+","+item.getMdate()+"\r\n";
            }
            result=new String(result.getBytes("utf-8"),"utf-8");
            //將字節流寫入response中
            response.getOutputStream().write(uft8bom);  //寫入頭部解決亂碼問題
            response.getOutputStream().write(result.getBytes("utf-8"));
            response.flushBuffer();
            response.getOutputStream().flush();
           
    }

}

獲取數據的來源大家應該都會了

上面的那句話不同瀏覽器可能會有不同

按照內容類型排列的 Mime 類型列表

類型/子類型擴展名
application/envoy evy
application/fractals fif
application/futuresplash spl
application/hta hta
application/internet-property-stream acx
application/mac-binhex40 hqx
application/msword doc
application/msword dot
application/octet-stream *
application/octet-stream bin
application/octet-stream class
application/octet-stream dms
application/octet-stream exe
application/octet-stream lha
application/octet-stream lzh
application/oda oda
application/olescript axs
application/pdf pdf
application/pics-rules prf
application/pkcs10 p10
application/pkix-crl crl
application/postscript ai
application/postscript eps
application/postscript ps
application/rtf rtf
application/set-payment-initiation setpay
application/set-registration-initiation setreg
application/vnd.ms-excel xla
application/vnd.ms-excel xlc
application/vnd.ms-excel xlm
application/vnd.ms-excel xls
application/vnd.ms-excel xlt
application/vnd.ms-excel xlw
application/vnd.ms-outlook msg
application/vnd.ms-pkicertstore sst
application/vnd.ms-pkiseccat cat
application/vnd.ms-pkistl stl
application/vnd.ms-powerpoint pot
application/vnd.ms-powerpoint pps
application/vnd.ms-powerpoint ppt
application/vnd.ms-project mpp
application/vnd.ms-works wcm
application/vnd.ms-works wdb
application/vnd.ms-works wks
application/vnd.ms-works wps
application/winhlp hlp
application/x-bcpio bcpio
application/x-cdf cdf
application/x-compress z
application/x-compressed tgz
application/x-cpio cpio
application/x-csh csh
application/x-director dcr
application/x-director dir
application/x-director dxr
application/x-dvi dvi
application/x-gtar gtar
application/x-gzip gz
application/x-hdf hdf
application/x-internet-signup ins
application/x-internet-signup isp
application/x-iphone iii
application/x-javascript js
application/x-latex latex
application/x-msaccess mdb
application/x-mscardfile crd
application/x-msclip clp
application/x-msdownload dll
application/x-msmediaview m13
application/x-msmediaview m14
application/x-msmediaview mvb
application/x-msmetafile wmf
application/x-msmoney mny
application/x-mspublisher pub
application/x-msschedule scd
application/x-msterminal trm
application/x-mswrite wri
application/x-netcdf cdf
application/x-netcdf nc
application/x-perfmon pma
application/x-perfmon pmc
application/x-perfmon pml
application/x-perfmon pmr
application/x-perfmon pmw
application/x-pkcs12 p12
application/x-pkcs12 pfx
application/x-pkcs7-certificates p7b
application/x-pkcs7-certificates spc
application/x-pkcs7-certreqresp p7r
application/x-pkcs7-mime p7c
application/x-pkcs7-mime p7m
application/x-pkcs7-signature p7s
application/x-sh sh
application/x-shar shar
application/x-shockwave-flash swf
application/x-stuffit sit
application/x-sv4cpio sv4cpio
application/x-sv4crc sv4crc
application/x-tar tar
application/x-tcl tcl
application/x-tex tex
application/x-texinfo texi
application/x-texinfo texinfo
application/x-troff roff
application/x-troff t
application/x-troff tr
application/x-troff-man man
application/x-troff-me me
application/x-troff-ms ms
application/x-ustar ustar
application/x-wais-source src
application/x-x509-ca-cert cer
application/x-x509-ca-cert crt
application/x-x509-ca-cert der
application/ynd.ms-pkipko pko
application/zip zip
audio/basic au
audio/basic snd
audio/mid mid
audio/mid rmi
audio/mpeg mp3
audio/x-aiff aif
audio/x-aiff aifc
audio/x-aiff aiff
audio/x-mpegurl m3u
audio/x-pn-realaudio ra
audio/x-pn-realaudio ram
audio/x-wav wav
image/bmp bmp
image/cis-cod cod
image/gif gif
image/ief ief
image/jpeg jpe
image/jpeg jpeg
image/jpeg jpg
image/pipeg jfif
image/svg+xml svg
image/tiff tif
image/tiff tiff
image/x-cmu-raster ras
image/x-cmx cmx
image/x-icon ico
image/x-portable-anymap pnm
image/x-portable-bitmap pbm
image/x-portable-graymap pgm
image/x-portable-pixmap ppm
image/x-rgb rgb
image/x-xbitmap xbm
image/x-xpixmap xpm
image/x-xwindowdump xwd
message/rfc822 mht
message/rfc822 mhtml
message/rfc822 nws
text/css css
text/h323 323
text/html htm
text/html html
text/html stm
text/iuls uls
text/plain bas
text/plain c
text/plain h
text/plain txt
text/richtext rtx
text/scriptlet sct
text/tab-separated-values tsv
text/webviewhtml htt
text/x-component htc
text/x-setext etx
text/x-vcard vcf
video/mpeg mp2
video/mpeg mpa
video/mpeg mpe
video/mpeg mpeg
video/mpeg mpg
video/mpeg mpv2
video/quicktime mov
video/quicktime qt
video/x-la-asf lsf
video/x-la-asf lsx
video/x-ms-asf asf
video/x-ms-asf asr
video/x-ms-asf asx
video/x-msvideo avi
video/x-sgi-movie movie
x-world/x-vrml flr
x-world/x-vrml vrml
x-world/x-vrml wrl
x-world/x-vrml wrz
x-world/x-vrml xaf
x-world/x-vrml

Q3:Excel導出的第二種方式

此方法需要導入幾個架包,需要的聯系我,我把壓縮包發給你

技術分享圖片

具體是哪一個我也不太清楚,所以我就全部導入了

--第一個類(Util),這個類用余測試數據,沒有數據庫連接

package ExcelUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

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.junit.Test;

public class Util {

    public static void main(String[] args) throws Exception {
        //writIntoExcel();
        testReadExcel();
        
    }
    public static void writIntoExcel(){
        
         /**
         * 註意這只是07版本以前的做法對應的excel文件的後綴名為.xls
         * 07版本和07版本以後的做法excel文件的後綴名為.xlsx
         */
        //創建新工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //新建工作表
        HSSFSheet sheet = workbook.createSheet("hello");
        //創建行,行號作為參數傳遞給createRow()方法,第一行從0開始計算
        HSSFRow row = sheet.createRow(0);
        //創建單元格,row已經確定了行號,列號作為參數傳遞給createCell(),第一列從0開始計算
        HSSFCell cell = row.createCell(2);
        //設置單元格的值,即C1的值(第一行,第三列)
        cell.setCellValue("hello china");
        //輸出到磁盤中
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(new File("D:11.xls"));
            workbook.write(fos);
            workbook.close();
            fos.close();
            System.out.println("寫入成功!");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    @Test
    public static void testReadExcel() throws Exception
    {
        //創建輸入流
        FileInputStream fis = new FileInputStream(new File("D:11.xls"));
        //通過構造函數傳參
        HSSFWorkbook workbook = new HSSFWorkbook(fis);
        //獲取工作表
        HSSFSheet sheet = workbook.getSheetAt(0);
        //獲取行,行號作為參數傳遞給getRow方法,第一行從0開始計算
        HSSFRow row = sheet.getRow(0);
        //獲取單元格,row已經確定了行號,列號作為參數傳遞給getCell,第一列從0開始計算
        HSSFCell cell = row.getCell(2);
        //設置單元格的值,即C1的值(第一行,第三列)
        String cellValue = cell.getStringCellValue();
        System.out.println("第一行第三列的值是"+cellValue);
        workbook.close();
        fis.close();
    }
}

--第二個類(ExcelControl),這個類可以連接數據庫

package ExcelUtil;
import java.io.FileOutputStream;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import dao.UinfoDao;
import vo.uinfo;

public class ExcelControl {
     /** 
     * @功能:手工構建一個簡單格式的Excel 
     */   
    /*private static List<uinfo> getMember() throws Exception  
    {  
        List list = new ArrayList();  
        SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");  
  
        //javabean 實體類
        uinfo user1 = new uinfo(1,"1998-05-13","男","廣東韶關");  
        uinfo user2 = new uinfo(2,"1999-10-13","女","廣東珠海");  
        uinfo user3 = new uinfo(3,"2000-07-13","男","廣東廣州");  
        list.add(user1);  
        list.add(user2);  
        list.add(user3);  
  
        return list;  
    } */ 
    private static UinfoDao uinfodao=new UinfoDao();
    public static List<uinfo> getMember(){
        List<uinfo>list=uinfodao.getAllUinfo();
        return list;
    }
    
    public static void main(String[] args) throws Exception  
    {  
        // 第一步,創建一個webbook,對應一個Excel文件  
        HSSFWorkbook wb = new HSSFWorkbook();  
         // 第二步,在webbook中添加一個sheet,對應Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("信息表一");  
        // 第三步,在sheet中添加表頭第0行,註意老版本poi對Excel的行數列數有限制short   
        HSSFRow row = sheet.createRow((int) 0);  
        // 第四步,創建單元格,並設置值表頭 設置表頭居中  
        HSSFCellStyle style = wb.createCellStyle();  
        style.setAlignment(HorizontalAlignment.CENTER);// 創建一個居中格式  
        HSSFCell cell = row.createCell((short) 0);  
        cell.setCellValue("編號");  
        cell.setCellStyle(style);  
        cell = row.createCell((short) 1);  
        cell.setCellValue("出生日期");  
        cell.setCellStyle(style);  
        cell = row.createCell((short) 2);  
        cell.setCellValue("性別");  
        cell.setCellStyle(style);  
        cell = row.createCell((short) 3);  
        cell.setCellValue("籍貫");
        cell.setCellStyle(style);  
  
        // 第五步,寫入實體數據 實際應用中這些數據從數據庫得到, 
        List list = ExcelControl.getMember();  
  
        for (int i = 0; i < list.size(); i++)  
        {  
            row = sheet.createRow((int) i + 1);  
            uinfo info = (uinfo) list.get(i);  
            // 第四步,創建單元格,並設置值  
            row.createCell((short) 0).setCellValue((double) info.getUid());  
            row.createCell((short) 1).setCellValue(info.getUsex());  
            row.createCell((short) 2).setCellValue((String)info.getUbirthday());  
            row.createCell((short) 3).setCellValue(info.getUaddress()); 
            //cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(info.getUaddress()));  
        }  
        // 第六步,將文件存到指定位置  
        try  
        {  
            FileOutputStream fout = new FileOutputStream("C:\\Users\\one\\Desktop\\Members.xls");  
            wb.write(fout);  
            fout.close();  
            System.out.println("寫入成功!");
        }  
        catch (Exception e)  
        {  
            e.printStackTrace();  
        }  
    }  
}

--上面從數據庫讀取文件就需要各位自己弄了,大家把代碼好好看看就明白了

教你學會下載圖片,文檔,excel導入導出