码迷,mamicode.com
首页 > Web开发 > 详细

Aspose.Cells导入导出

时间:2016-07-04 11:46:51      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:

插件: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>
View Code


导入: 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
 
关于MVC4.0 WebAPI上传图片重命名以及图文结合
 
ASP.NET Web Api Self Host大文件上传功能
 
 
首发地址:http://www.yuanxj.net/2014/02/upladfile/

Aspose.Cells导入导出

标签:

原文地址:http://www.cnblogs.com/love201314/p/5639675.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!