版本:Mongodb2.4.8

通过页面下载Excel文件

jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="post">
<a href="/Demo/DownDemo"><h2>下载</h2></a>
</form>
</body>
</html>

  Mongodb配置文件dbconfig.properties:

url=localhost
port=27017
db=movie
table=mv

  连接Mongodb工具类:

package util;
import java.io.IOException;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.Properties;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
public class DBConn {
private static String url;
private static int port;
private static String db;
private static String table;
// 初始化加载
static{
//加载
Properties p = new Properties();
InputStream input = DBConn.class.getClassLoader().getResourceAsStream("dbconfig.properties");
try {
p.load(input);
url = p.getProperty("url");
port = Integer.valueOf(p.getProperty("port"));
db = p.getProperty("db");
table = p.getProperty("table");
} catch (IOException e) {
e.printStackTrace();
}finally{
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 获取连接mongodb
* @Description:
* @param @return
* @return DBCollection 返回类型
*/
public static DBCollection getConn(){
DBCollection conn = null;
try {
Mongo m = new Mongo(url,port);
DB d = m.getDB(db);
conn = d.getCollection(table);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
return conn;
}
/**
* 关闭连接
* @Description:
* @param @param m
* @return void 返回类型
*/
public static void getClose(Mongo m){
m.close();
}
}

  读取Mongodb数据写入到excel中:

public class WriteExcelUtils {
/**
* @Description:mongdb中读取数据写入到Excel
* @param title
* @param filename
* @param rownum
* @param cursor
* @return void 返回类型
*/
public static void Excel(DBCursor cursor,OutputStream out) {
Workbook book = new HSSFWorkbook();
// 获取标题
DBObject ob = cursor.toArray().get(0);
ArrayList<String> title = new ArrayList<>();
for(String key:ob.keySet()){
if (key.equals("_id")) {
continue;
}
title.add(key);
}
// 创建sheet
Sheet sheet = book.createSheet();
try {
// 写入标题栏
Row row = null;
// 标题栏的行数
Cell cell = null;
for(int i = 0;i< (cursor.count() + 1);i++){
// 标题栏
if (i == 0) {
row = sheet.createRow(i);
for (int j = 0; j < title.size(); j++) {
cell = row.createCell(j);
// 设置标题栏
cell.setCellValue(title.get(j));
}
continue;
}
// 写入数据
row = sheet.createRow(i);
DBObject obj = null;
for (int j = 0; j < title.size(); j++) {
cell = row.createCell(j);
obj = cursor.toArray().get(j);
for(String key :obj.keySet()){
if (key.equals("_id")) {
continue;
}
if (key.equals(title.get(j))) {
cell.setCellValue((String)(obj.get(key)));
}
}
}
}
// 写入到excel
book.write(out);
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
} }
}

  Servlet:

package servlet;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject; import util.DBConn;
import util.WriteExcelUtils; /**
* Servlet implementation class DownDemo
*/
@WebServlet("/DownDemo")
public class DownDemo extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public DownDemo() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
getMongodbExcle(request, response);
} /**
* 从mongdb中读取数据下载到客户端
* @Description:
* @param request
* @param response
* @return void 返回类型
*/
private void getMongodbExcle(HttpServletRequest request, HttpServletResponse response){
// 设置请求
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=data.xls");
// 从mongodb中读取数据
DBCollection conn = DBConn.getConn();
DBCursor cursor = conn.find();
OutputStream out = null;
try {
out = new BufferedOutputStream(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
WriteExcelUtils.Excel(cursor,out); }
}

  

在线读取Mongodb数据库下载EXCEL文件的更多相关文章

  1. SQLBulkCopy使用实例--读取Excel写入数据库/将 Excel 文件转成 DataTable

    MS SQL Server 提供一个称为 bcp 的流行的命令提示符实用工具,用于将数据从一个表移动到另一个表(表可以在不同服务器上). SqlBulkCopy 类允许编写提供类似功能的托管代码解决方 ...

  2. C# 之 下载EXCEL文件,自动用迅雷下载aspx

    在浏览器中导出 Excel 得时候,如果浏览器绑定了迅雷,则会下载aspx文件. 解决:下载EXCEL文件,自动用迅雷下载aspx if (Request.QueryString["id&q ...

  3. 前端下载excel文件功能的三种方法

    1 从后端接收json数据,前端处理生成excel下载 JsonExportExcel的github地址:https://github.com/cuikangjie/JsonExportExcel 这 ...

  4. 前端调用后端接口下载excel文件的几种方式

    今天有一个导出相应数据为excel表的需求.后端的接口返回一个数据流,一开始我用axios(ajax类库)调用接口,返回成功状态200,但是!但是浏览器没有自动下载excel表,当时觉得可能是ajax ...

  5. jsp下载excel文件

    jsp下载excel文件的的实现方法很多,今天也遇到这个问题,乱敲了一阵,终于搞定了,记下来和朋友们分享吧. 假设需要下载excel文件的jsp页面名为:down.jsp 对应的后台action名为: ...

  6. asp.net 下载EXCEL文件

    一.需要导入NPOI 库文件 打开VS2012 工具>>库程序包管理器>>管理解决方案的NuGet程序包,搜索NPOI,如下图 安装完成: 添加 using NPOI.HSSF ...

  7. c# 用OpenXmL读取.xlsx格式的Excel文件 返回DataTable

    1.须要引用的dll :  DocumentFormat.OpenXml.dll  ---须要安装一下OpenXml再引用 WindowsBase  ---直接在项目里加入引用 2.方法: /// & ...

  8. 读取FTP上的excel文件,并写入数据库

    今天遇到一些问题,需要从ftp上读取一些excel文件,并需要将excel中的数据写入到数据库,这样就可以通过管理页面查看这些数据. 我将相关工作分为三步,1.从ftp上读取相关文件,并将excel文 ...

  9. [转] 从数据库中读取图片并导入Excel文件,C#方式

    原文地址, 作者 Lvyou1980 直接源码吧. using System; using System.IO; using System.Data; using System.Drawing; us ...

随机推荐

  1. [转]人人网首页拖拽上传详解(HTML5 Drag&Drop、FileReader API、formdata)

    人人网首页拖拽上传详解(HTML5 Drag&Drop.FileReader API.formdata) 2011年12月11日 | 彬Go 上一篇:给力的 Google HTML5 训练营( ...

  2. 【leetcode❤python】Binary Watch

    #-*- coding: UTF-8 -*- from itertools import combinationsclass Solution(object):        hourList=[8, ...

  3. An Example Of Validating Text Item In Oracle Forms Using When-Validate-Item Trigger

    Example is given below to validate a Text Item in Oracle Forms with specific rules condition which c ...

  4. [HDOJ5289]Assignment(RMQ,二分)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5289 题意:求满足区间内最大值和最小值差为k的区间个数. 预处理出区间的最值,枚举左端点,根据最值的单 ...

  5. [SAP ABAP开发技术总结]日期函数

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

  6. ServiceStack.OrmLite 笔记8 -还是有用的姿势

    复杂点的使用2 InsertAll, UpdateAll and DeleteAll 的参数要是IEnumerables Each关键字 返回 IEnumerable 并且是延迟加载的 全局设置 当字 ...

  7. NoSql存储日志数据之Spring+Logback+Hbase深度集成

    NoSql存储日志数据之Spring+Logback+Hbase深度集成 关键词:nosql, spring logback, logback hbase appender 技术框架:spring-d ...

  8. python_way day15 HTML-DAY2 HTML-DAY2、JS

    python_way day15 HTML-DAY2 html-css回顾 javascript 一.html-css回顾 1.input与+,-号的写法 <!DOCTYPE html> ...

  9. 细心看完这篇文章,刷新对Javascript Prototype的理解

    var person={name:'ninja'}; person.prototype.sayName=function(){ return this.name; } 分析上面这段代码,看看有没有问题 ...

  10. javascript知识总汇

    命名: 变量名和函数命名:第一个单词小写以后每个单词首字母大写.geteElementById() 对象命名:每个单词首字母大写. 数据类型 typeof()方法返回数据类型. number数据类型: ...