插件:Aspose.Cells

没有安装office插件也能使用;

导出:不能使用ajax异步·

        /// <summary>
/// 导出试题
/// </summary>
/// <param name="userId">用户Id</param>
/// <param name="courseId">课程Id</param>
/// <returns></returns>
[HttpGet]
public FilePathResult ExportQuestions(int userId, int courseId)
{
// 工作薄
Workbook BuildReport_WorkBook = new Workbook();
//sheets集合
Worksheets sheets = BuildReport_WorkBook.Worksheets;
//试题表
Worksheet BuildReport_WorkSheet = BuildReport_WorkBook.Worksheets[]; // sheet1
BuildReport_WorkBook.Worksheets[].Name = "试题表";
BuildReport_WorkSheet.FreezePanes(, , , ); //冻结第一行
BuildReport_WorkSheet.AutoFitColumns();//让各列自适应宽度
Cells BuildReportCells = BuildReport_WorkSheet.Cells; //单元格 //表头
BuildReportCells[, ].PutValue("试题Id");
BuildReportCells[, ].PutValue("课程Id");
BuildReportCells[, ].PutValue("试题类型"); //第二个sheet
BuildReport_WorkBook.Worksheets.Add("试题描述");
Worksheet BuildReport_WorkSheet_Desc = BuildReport_WorkBook.Worksheets["试题描述"]; //sheet2
BuildReport_WorkSheet_Desc.FreezePanes(, , , ); //冻结第一行
Cells BuildReportCells_Desc = BuildReport_WorkSheet_Desc.Cells; //表头
BuildReportCells_Desc[, ].PutValue("试题描述Id");
BuildReportCells_Desc[, ].PutValue("试题Id");
BuildReportCells_Desc[, ].PutValue("试题描述");
BuildReportCells_Desc[, ].PutValue("试题解析");
BuildReportCells_Desc[, ].PutValue("试题描述(不包含html字符)"); //列
BuildReportCells[i, ].PutValue(item.Id);
BuildReportCells[i, ].PutValue(item.CourseId);
BuildReportCells[i, ].PutValue(item.QuestionType); BuildReportCells_Desc[j, ].PutValue(questionDesc.ID);
BuildReportCells_Desc[j, ].PutValue(questionDesc.QuestionId);
BuildReportCells_Desc[j, ].PutValue(questionDesc.Description);
BuildReportCells_Desc[j, ].PutValue(questionDesc.Analyses); //文件路径
string fileDirPath = "/Downloads/试题" + userId + "_" + courseId;
string downPath = Server.MapPath(fileDirPath);
if (!Directory.Exists(downPath))
{
Directory.CreateDirectory(downPath);
}
System.IO.File.SetAttributes(downPath, FileAttributes.Normal); string nowTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string tempFile = Path.GetTempFileName();
string saveFile = Server.MapPath(fileDirPath + "/" + "试题" + "_" + userId + "_" + courseId + ".xls");
BuildReport_WorkBook.Save(saveFile); return File(saveFile, "application/octet-stream", "试题" + "_" + userId + "_" + courseId + ".xls");
}

导出

导入: view,

需要注意2个问题:
1. 注意给form表单加上enctype = "multipart/form-data" 属性,否则会导致Action的参数HttpPostedFileBase 对象接收不到文件。
2. 注意文件大小,IIS中默认上传的文件大小为4MB ,超过这大小的文件需要在修改配置文件。
 

<div  style="display:none" >
<div id="divImportQuestions" class="easyui-dialog" title="导入试题" closed="true" style="width:400px;height:200px;padding:10px;" data-options="iconCls:'icon-save',modal:true">
@using (Html.BeginForm("ImportQuestions", "ManageCourse", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmImport" }))
{
<input id="fileImport" type="file" name="fileImport" />
<div style="padding:5px;text-align:center;">
<a id="btnCommit" href="javascript:void(0);" onclick="ImportQuestions()" class="easyui-linkbutton" iconcls="icon-ok">确 定</a>
<a href="javascript:void(0);" onclick="top.ClosedlgWindow();" class="easyui-linkbutton" iconcls="icon-cancel">取 消</a>
</div>
<input id="hidUserId" type="hidden" name="hidUserId" />
<input id="hidCourseId" type="hidden" name="hidCourseId" />
<input id="hidUserName" type="hidden" name="hidUserName" />
}
@*<form id="frmImport" action="/admin/ManageCourse/ImportQuestions" method="post" enctype="multipart/form-data">
<input id="fileImport" type="file" name="fileImport" />
<div style="padding:5px;text-align:center;">
<a id="btnCommit" href="javascript:void(0);" onclick="ImportQuestions()" class="easyui-linkbutton" iconcls="icon-ok">确 定</a>
<a href="javascript:void(0);" onclick="top.ClosedlgWindow();" class="easyui-linkbutton" iconcls="icon-cancel">取 消</a>
</div>
<input id="hidUserId" type="hidden" name="hidUserId" />
<input id="hidCourseId" type="hidden" name="hidCourseId" />
</form>*@
</div>
</div>

导入: controller

/// <summary>
/// 导入试题
/// </summary>
/// <param name="userId">用户Id</param>
/// <param name="courseId">课程Id</param>
/// <returns>int userId, int courseId,</returns>
[HttpPost]
public ActionResult ImportQuestions(HttpPostedFileBase upFileBase)
{
HttpPostedFileBase fileBase = Request.Files["fileImport"];
if (fileBase != null)
{
#region 保存文件 string fileName = Path.GetFileName(fileBase.FileName);
string fileNameNoExt = Path.GetFileNameWithoutExtension(fileBase.FileName);
string extension = Path.GetExtension(fileName);
//if (extension.ToLower() != ".zip") //extension.ToLower() != ".xls" || extension.ToLower() != ".xlsx" ||
//{
// //window.location.href='@Url.Action('a','b')'
// return Content("<script type='text/javascript'>alert('请上传zip格式的压缩文件');window.location.href='/admin/ImportQuestions';</script>");
//} string filePath = "/UploadFile/试题/"; // +DateTime.Now.ToString("yyyyMMdd") + "/"; if (!Directory.Exists(Server.MapPath(filePath))) //文件夹
{
Directory.CreateDirectory(Server.MapPath(filePath));
}
string nowTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string fullFileName = Server.MapPath(filePath + nowTime + "_" + userId + "_" + courseId + "_" + fileName);//文件名
fileBase.SaveAs(fullFileName); //保存在服务器 #endregion string fileFullName = Path.Combine(strFileUrl, Path.GetFileName(file.Name)); #region 导入EXECL Workbook BuildReport_WorkBook = new Workbook();
BuildReport_WorkBook.Open(fileFullName); Worksheets sheets = BuildReport_WorkBook.Worksheets; //试题表
Worksheet workSheetQuestion = BuildReport_WorkBook.Worksheets["试题表"]; // sheet1
Cells cellsQuestion = workSheetQuestion.Cells; //单元格
Worksheet workSheetDesc = BuildReport_WorkBook.Worksheets["试题描述"]; //sheet2
Cells cellsDesc = workSheetDesc.Cells; //试题表
for (int i = ; i < cellsQuestion.MaxDataRow + ; i++)
{
#region 试题表 Question modQuestion = new Question();//实体
int questionId = cellsQuestion[i, ].IntValue;
dicQuestion[i] = cellsQuestion[i, ].IntValue;
modQuestion.CourseId = cellsQuestion[i, ].IntValue;
modQuestion.QuestionType = cellsQuestion[i, ].IntValue; //数据库操作 } for (int j = ; j < cellsDesc.MaxDataRow + ; j++)
{
int questionDescFK = cellsDesc[j, ].IntValue;
if (questionId == questionDescFK)
{
Question_Desc modQuestionDesc = new Question_Desc(); //实体
modQuestionDesc.QuestionId = questionIdNew; //新的
modQuestionDesc.Description = cellsDesc[j, ].StringValue.Trim();
modQuestionDesc.Analyses = cellsDesc[j, ].StringValue.Trim();
modQuestionDesc.DescriptionText = cellsDesc[j, ].StringValue.Trim(); //数据库操作
}
} #endregion } return View();
}

导入Controller

● 由于接收多个文件,所以控制器方法的参数变成了IEnumerable<HttpPostedFileBase> files
● 变量files与前台视图的name属性值对应
● 如果没有指定的文件夹,就创建一个文件夹

为什么使用HttpPostedFileBase而不是FormCollection来接收文件

public sealed class FormCollection : NameValueCollection, IValueProvider

可见,FormCollection是键值集合,键是string类型,值是string类型,而上传的文件类型不是string,所以不能用FormCollection作为参数来接收文件。

参考资料:
 

MVC中的文件上传http://blog.sina.com.cn/s/blog_75a555e40101q8i7.html

 
Confusing required maxRequestLength and maxAllowedContentLength settings
 
关于MVC4.0 WebAPI上传图片重命名以及图文结合
 
ASP.NET Web Api Self Host大文件上传功能
 
 
首发地址:http://www.yuanxj.net/2014/02/upladfile/

Aspose.Cells导入导出execl的更多相关文章

  1. Aspose.Cells 导入导出EXCEL(转)

    Aspose.Cells 导入导出EXCEL      修改样式        Workbook workbook = new Workbook(); //工作簿          Worksheet ...

  2. NPOI、MyXls、Aspose.Cells 导入导出Excel(转)

    Excel导入及导出问题产生: 从接触.net到现在一直在维护一个DataTable导s出到Excel的类,时不时还会维护一个导入类.以下是时不时就会出现的问题: 导出问题: 如果是asp.net,你 ...

  3. C# WinForm使用Aspose.Cells.dll 导出导入Excel/Doc 完整实例教程

    1.添加引用: Aspose.Cells.dll(我们就叫工具包吧,可以从网上下载.关于它的操作我在“Aspose.Cells操作说明 中文版 下载 Aspose C# 导出Excel 实例”一文中的 ...

  4. Aspose.Cells.dll操作execl

    附件:Aspose.Cells.dll 1.创建execl(不需要服务器或者客户端安装office) public void DCExexl(DataTable dt) {  Workbook wb ...

  5. Asp.net & Aspose.cells 导入

    Workbook workBook = new Workbook(this.fuFile.FileContent); Aspose.Cells.Worksheet sheet = workBook.W ...

  6. 依赖Aspose.Cells Excel 导出

    public static void SaveExcel() { //新建工作簿 Workbook workbook = new Workbook(); //工作簿 Worksheet sheet = ...

  7. Aspose.Cells.dll引用导入导出Excel

    Aspose.Cells 导入导出EXCEL 文章出处:http://hi.baidu.com/leilongbing/item/c11467e1819e5417595dd8c1 修改样式       ...

  8. C# WinForm 导出导入Excel/Doc 完整实例教程[使用Aspose.Cells.dll]

    [csharp] view plain copy 1.添加引用: Aspose.Cells.dll(我们就叫工具包吧,可以从网上下载.关于它的操作我在“Aspose.Cells操作说明 中文版 下载 ...

  9. 【转】 (C#)利用Aspose.Cells组件导入导出excel文件

    Aspose.Cells组件可以不依赖excel来导入导出excel文件: 导入: public static System.Data.DataTable ReadExcel(String strFi ...

随机推荐

  1. Django之博客系统搭建一

    前面已经介绍了django的各种用法,从这一章开始,将实际搭建一个blog系统. 首先我们需要设计blog的模型,在models.py中添加如下内容 # -*- coding: utf-8 -*- f ...

  2. vtk-py z-Buffer可见算法

    C++版例子: https://lorensen.github.io/VTKExamples/site/Cxx/PolyData/SelectVisiblePoints/ 优点: Simple to ...

  3. Java之批处理的实现

    批处理(batch) 一.批处理介绍 1. 批处理指的是一次操作中执行多条SQL语句 2. 批处理相比于一次一次执行效率会提高很多 3. 批处理主要是分两步: 1.将要执行的SQL语句保存 2.执行S ...

  4. C语言数据结构-单链表的实现-初始化、销毁、长度、查找、前驱、后继、插入、删除、显示操作

    1.数据结构-单链表的实现-C语言 typedef struct LNode { int data; struct LNode* next; } LNode,*LinkList; //这两者等价.Li ...

  5. P3380 【模板】二逼平衡树(树套树) 线段树套平衡树

    \(\color{#0066ff}{ 题目描述 }\) 您需要写一种数据结构(可参考题目标题),来维护一个有序数列,其中需要提供以下操作: 查询k在区间内的排名 查询区间内排名为k的值 修改某一位值上 ...

  6. P1114 “非常男女”计划

    题意:给你一个01串,求满足0和1总数相等的最大字串   $n\ \le\ 10^5$ 1.$O(n^3)$枚举起点终点,统计判断是否成立 2.$O(n^2)$先$O(n)$时间计算01个数的前缀和, ...

  7. 黑马学习CSS选择器 简单选择器 结合符 选择器组合 选择器优先级

  8. pytorch构建优化器

    这是莫凡python学习笔记. 1.构造数据,可以可视化看看数据样子 import torch import torch.utils.data as Data import torch.nn.func ...

  9. element el-tree循环遍历树形结构,并动态赋值disabled属性

    凌晨3点,功夫不负有心人,已经累趴,效果终于出来: 贴上代码: <style scoped> .form { width: 50%; } </style> <templa ...

  10. java 反射 处理 空值

    package org.zkdg.utils.spring.annotations.impl; import java.lang.annotation.Annotation; import java. ...