教你学会下载图片,文档,excel导入导出

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();
        }
    }
}

--上面从数据库读取文件就需要各位自己弄了,大家把代码好好看看就明白了

原文地址:https://www.cnblogs.com/zywds/p/9362310.html

时间: 2024-10-10 13:49:29

教你学会下载图片,文档,excel导入导出的相关文章

Asp.net的对Excel文档的导入导出操作

刚刚初入职场,在休闲的时间写下了项目中用到的对Excel文档操作的方法以及总结,多的不说,直接上代码 public static void CreateExcel(DataSet ds, string FileName) { //resp = Page.Response; HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.Ch

Angular/Spring Boot Rest API下载Word文档

POI生成Word文档 使用POI XWPF生成Word文档,引入POI: <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.0</version> </dependency> 项目中经常从Word模板生成文档,下面示例演示了替换文档内容的方法.模版中要替换的内容以${}标

手动下载 Xcode 文档

下载Xcode文档的方法有两个: 1. 自动下载:到在Xcode的Preserences中Downloads页面的Documentation,点击对应文档的下载. 不建议勾选下面的Check for and install updates automatically,因为下载过程中可能无法正常使用Documents. 2. 手动下载:到这个页面:https://developer.apple.com/library/downloads/docset-index.dvtdownloadablein

百度文库免费下载网站(只能下载点券文档)

百度文库免费下载网站:https://baidu3888.com,不要把https去掉哈 笔者最近发现了一个不错的网站,可以免费下载百度文库中需要点券的文档(不论文档需要的点券是多少,每次下载只需要支付5毛钱,笔者觉得还是很划算的). 目前网上有一些号称能下载百度文库的软件大都是假的,或者是OCR抓取的,不是百度文库原有格式: 某电商网站上有代下载服务,但是价格都比较高,而且个别店铺兜售账户是骗子(账户有下载次数限制,有使用时间限制等): 温馨提示:凡是号称能下载付费文档的,大都价格高昂,基本都

扫描的PDF文档快速导入书签栏

扫描的PDF文档快速导入书签栏 1.  将带标题的Word生成PDF文档,Word导出的PDF文档是带有标签,操作如下: 2.  下载绿色软件FreePic2Pdf,打开选择更改PDF: 3.   首先从PDF中摘取书签,选择Word导出PDF文件,选择新的文件地址生成书签数据: 4.  生成的书签数据如下: 5.  往扫描版PDF挂书签,点击开始: 书签生成,灰常好用. 原文地址:https://www.cnblogs.com/CSZhang/p/12568483.html

java jxl excel 导入导出的 总结(建立超链接,以及目录sheet的索引)

最近项目要一个批量导出功能,而且要生成一个单独的sheet页,最后后面所有sheet的索引,并且可以点击进入连接.网上搜索了一下,找到一个方法,同时把相关的excel导入导出操作记录一下!以便以后使用! 简单先写一下目录的建立的主要代码,测试用的 List ls = new ArrayList();//报表名称列表  ls.add("BB_BB03");  ls.add("BB_BB05");  ls.add("BB_BB06"); try { 

Excel导入导出的业务进化场景及组件化的设计方案(转)

1:前言 看过我文章的网友们都知道,通常前言都是我用来打酱油扯点闲情的. 自从写了上面一篇文章之后,领导就找我谈话了,怕我有什么想不开. 所以上一篇的(下)篇,目前先不出来了,哪天我异地二次回忆的时候,再分享分享. 话说最近外面IT行情飞涨还咋的,人都飞哪去了呢,听说各地的军情都进入紧急状态了. 回归下正题,今天就抽点时间,写写技术文,和大伙分享一下近年在框架设计上的取的一些技术成果. 2:项目背景 在针对运营商(移动.联通.电信.铁塔)的信息类的系统中,由于相关的从业人员习惯于Excel的办公

excel导入导出优化

对于上一篇excel中出现的问题,在excel导入导出中都做了优化.还是eclipse+jdk1.8,但是这个项目是一个web项目,需要配合Tomcat服务器,并且使用了SSH框架, I/O操作过多 首先,对于I/O操作过多,那么就不像之前一样,一条一条的添加或者更新;而且凑齐一堆,也就是一个list集合,然后统一的批量保存. 使用SessionFactory获取当前的session,然后调用session的persist方法,保存实体.只是设置了一个批量的量值.每到30条数据,就将缓存同步到数

一个基于POI的通用excel导入导出工具类的简单实现及使用方法

前言: 最近PM来了一个需求,简单来说就是在录入数据时一条一条插入到系统显得非常麻烦,让我实现一个直接通过excel导入的方法一次性录入所有数据.网上关于excel导入导出的例子很多,但大多相互借鉴.经过思考,认为一百个客户在录入excel的时候,就会有一百个格式版本,所以在实现这个功能之前,所以要统一excel的格式.于是提供了一个通用excel模版的下载功能.当所有客户用模版录入好数据再上传到系统,后端对excel进行解析,然后再持久化到数据库. 概述: 此工具类的几大特点 1.基本导入导出