Aspose.Cells导入导出

插件: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[0];   //  sheet1
            BuildReport_WorkBook.Worksheets[0].Name = "试题表";
            BuildReport_WorkSheet.FreezePanes(1, 1, 1, 0); //冻结第一行
            BuildReport_WorkSheet.AutoFitColumns();//让各列自适应宽度
            Cells BuildReportCells = BuildReport_WorkSheet.Cells;    //单元格

            //表头
            BuildReportCells[0, 0].PutValue("试题Id");
            BuildReportCells[0, 1].PutValue("课程Id");
            BuildReportCells[0, 2].PutValue("试题类型");

            //第二个sheet
            BuildReport_WorkBook.Worksheets.Add("试题描述");
            Worksheet BuildReport_WorkSheet_Desc = BuildReport_WorkBook.Worksheets["试题描述"];  //sheet2
            BuildReport_WorkSheet_Desc.FreezePanes(1, 1, 1, 0); //冻结第一行
            Cells BuildReportCells_Desc = BuildReport_WorkSheet_Desc.Cells;

            //表头
            BuildReportCells_Desc[0, 0].PutValue("试题描述Id");
            BuildReportCells_Desc[0, 1].PutValue("试题Id");
            BuildReportCells_Desc[0, 2].PutValue("试题描述");
            BuildReportCells_Desc[0, 3].PutValue("试题解析");
            BuildReportCells_Desc[0, 4].PutValue("试题描述(不包含html字符)");

            //列
            BuildReportCells[i, 0].PutValue(item.Id);
            BuildReportCells[i, 1].PutValue(item.CourseId);
            BuildReportCells[i, 2].PutValue(item.QuestionType);

            BuildReportCells_Desc[j, 0].PutValue(questionDesc.ID);
            BuildReportCells_Desc[j, 1].PutValue(questionDesc.QuestionId);
            BuildReportCells_Desc[j, 2].PutValue(questionDesc.Description);
            BuildReportCells_Desc[j, 3].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 = 1; i < cellsQuestion.MaxDataRow + 1; i++)
                {
                    #region 试题表

                    Question modQuestion = new Question();//实体
                    int questionId = cellsQuestion[i, 0].IntValue;
                    dicQuestion[i] = cellsQuestion[i, 0].IntValue;
                    modQuestion.CourseId = cellsQuestion[i, 1].IntValue;
                    modQuestion.QuestionType = cellsQuestion[i, 2].IntValue;

                    //数据库操作

                }

                for (int j = 1; j < cellsDesc.MaxDataRow + 1; j++)
                {
                    int questionDescFK = cellsDesc[j, 1].IntValue;
                    if (questionId == questionDescFK)
                    {
                        Question_Desc modQuestionDesc = new Question_Desc(); //实体
                        modQuestionDesc.QuestionId = questionIdNew;  //新的
                        modQuestionDesc.Description = cellsDesc[j, 2].StringValue.Trim();
                        modQuestionDesc.Analyses = cellsDesc[j, 3].StringValue.Trim();
                        modQuestionDesc.DescriptionText = cellsDesc[j, 4].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

http://forums.iis.net/t/1169846.aspx

关于MVC4.0 WebAPI上传图片重命名以及图文结合

http://www.cnblogs.com/ang/archive/2012/10/24/2634176.html

ASP.NET Web Api Self Host大文件上传功能

http://www.cnblogs.com/fenglin1985/archive/2013/01/29/2879926.html

首发地址:http://www.yuanxj.net/2014/02/upladfile/

时间: 2024-10-13 02:49:01

Aspose.Cells导入导出的相关文章

NPOI与Aspose的导入导出保存

半个月没进博客园了,终于把网站做完了,想想毕业快一年的时间里,都是去学习新的计算,现在也该总结下用到的代码,慢慢整理整理,就先从最简单的导入导出开始吧 一:首先看下国人开发的NPOI的导入导出 项目的Office的操作模块图为:        ,现在贴上导入导出类的代码 (1)导入类 public class ExcelForImport : IImport { protected static ExcelForImport _instance; private static object lo

Asp.net &amp; Aspose.cells 导入

1 Workbook workBook = new Workbook(this.fuFile.FileContent); 2 Aspose.Cells.Worksheet sheet = workBook.Worksheets[0]; 3 Cells cells = sheet.Cells; 4 5 //DataTable dt = cells.ExportDataTable(0, 0, cells.MaxRow + 1, cells.MaxDataColumn + 1, true); 6 Da

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

Aspose.Cells 导入导出EXCEL 文章出处:http://hi.baidu.com/leilongbing/item/c11467e1819e5417595dd8c1 修改样式       Workbook workbook = new Workbook(); //工作簿 Worksheet sheet = workbook.Worksheets[0]; //工作表 Cells cells = sheet.Cells;//单元格 //样式2 Aspose.Cells.Style st

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

Aspose.Cells组件可以不依赖excel来导入导出excel文件: 导入: [csharp] view plain copy print? public static System.Data.DataTable ReadExcel(String strFileName) { Workbook book = new Workbook(); book.Open(strFileName); Worksheet sheet = book.Worksheets[0]; Cells cells = 

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

Aspose.Cells组件可以不依赖excel来导入导出excel文件: 导入: public static System.Data.DataTable ReadExcel(String strFileName) { Workbook book = new Workbook(); book.Open(strFileName); Worksheet sheet = book.Worksheets[0]; Cells cells = sheet.Cells; return cells.Export

aspose.cells excel表格导入导出

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Reflection; using System.IO; using Aspose.Cells; using System.Data; using System.ComponentModel; using System.Configuration; namespace src.Common { publ

C# WinForm 导出导入Excel/Doc [使用Aspose.Cells.dll]

参考地址:http://blog.csdn.net/az44yao/article/details/7656074 private void DatatableToExcel(DataTable dgv, string Title) { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Execl files (*.xls)|*.xls"; dlg.CheckFileExists = false; dlg.CheckPat

在ASP.NET MVC中利用Aspose.cells 将查询出的数据导出为excel,并在浏览器中下载。

正题前的唠叨 本人是才出来工作不久的小白菜一颗,技术很一般,总是会有遇到一些很简单的问题却不知道怎么做,这些问题可能是之前解决过的.发现这个问题,想着提升一下自己的技术水平,将一些学的新的'好'东西记录下来,一是加深印象:二是以后可以作为参考:三是希望博友们可以提出不足和可以优化的地方,一起讨论. 这个是我去一家公司没多久,让我做的小功能,主要是导出excel并在浏览器下载下来. 但是会有不同的细微的需求差别. 第一次发博客,有描述不清楚的地方还请见谅,希望各位多多指点. 进入正题 简单的需求描

利用Aspose.Cells完成easyUI中DataGrid数据的Excel导出功能

我准备在项目中实现该功能之前,google发现大部分代码都是利用一般处理程序 HttpHandler实现的服务器端数据的Excel导出,但是这样存在的问题是ashx读取的数据一般都是数据库中视图的数据,难免会含有方便操作的 主键ID这列的记录.现在项目需要在easyUI的DataGrid中显示的数据能全部导出Excel,包括DataGrid中的中文标题,其他的统统不 要. 完成该功能所需的工具和环境:Newtonsoft.Json序列化和反序列化类库.easyUI前端UI框架.HttpHandl