C# Excel导入
两张表导入到一个DataGrid里面(题目表和答案表)
前台代码
- <asp:Content ID="Content1" ContentPlaceHolderID="cphToolBar" runat="server">
- <epoint:Button ID="btnImport" runat="server" Text="题库信息导入" />
- <span>
- <span style="color: red;">模板下载:</span><a target="_blank"
- href="题库模版.xls"><span style="color: blue;">点击下载文件</span> </a>
- </span>
- </asp:Content>
- <asp:UpdatePanel runat="server" ID="UpdatePanel_Upload">
- <ContentTemplate>
- <epoint:CuteWebUIUpload_NoBut ID="upload1" AllowFileList="xlsx;xls" runat="server"
- MaxAttachCount="-1" MaxAttachCountOneTime="" UseCustomSaveMethod="true" OnFileUploadCompleted_Custom="upload1_FileUploadCompleted_Custom" />
- </ContentTemplate>
- </asp:UpdatePanel>
后台代码
- /// <summary>
- /// 导入
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="args"></param>
- protected void upload1_FileUploadCompleted_Custom(object sender, EventArgsOperate.AttachEventArgs[] args)
- {
- if (!Directory.Exists(Server.MapPath(@"ImportExcel")))
- Directory.CreateDirectory(Server.MapPath(@"ImportExcel"));
- string mark = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString();
- string oldfileName = args[].FileName;
- string documentType = oldfileName.Substring(oldfileName.LastIndexOf('.'), oldfileName.Length - oldfileName.LastIndexOf('.'));
- string fileName = "Import_" + mark + documentType;
- args[].CuteArgs.CopyTo(Server.MapPath(@"ImportExcel\") + fileName);
- ReadExcel(Server.MapPath(@"ImportExcel\") + fileName);
- }
- public void ReadExcel(string ExcelFile)
- {
- DataSet ds;
- string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFile + ";" + "Extended Properties='Excel 12.0';";
- OleDbConnection conn = new OleDbConnection(strConn);
- DataTable dtExcelSchema = new DataTable();
- try
- {
- conn.Open();
- dtExcelSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
- new object[] { null, null, null, "Table" });//获取需要上传的Excel的Sheet
- conn.Close();
- }
- catch
- {
- throw;
- }
- for (int k = ; k <= dtExcelSchema.Rows.Count; k++)
- {
- try
- {
- ds = new DataSet();
- OleDbDataAdapter oada = new OleDbDataAdapter("select * from [Sheet" + k + "$]", strConn);
- oada.Fill(ds);
- }
- catch
- {
- throw;
- }
- DataTable dt = ds.Tables[];
- if (dt.Rows.Count > )
- {
- for (int i = ; i < dt.Rows.Count; i++)
- {
- M_Exam_Subject m_es = new M_Exam_Subject();
- M_Exam_Answer m_ea = new M_Exam_Answer();
- #region 插入题目
- m_es.SubjectGuid = NewSubjectGuid();
- m_es.Title = Convert.ToString(dt.Rows[i][]);//题目名称
- string type = Convert.ToString(dt.Rows[i][]);//题目类型
- switch (type)
- {
- case "单选": m_es.Type = "";
- break;
- case "多选": m_es.Type = "";
- break;
- case "判断": m_es.Type = "";
- break;
- case "填空": m_es.Type = "";
- break;
- case "简答": m_es.Type = "";
- break;
- }
- string difficult = Convert.ToString(dt.Rows[i][]);//题目难度
- switch (difficult)
- {
- case "简单": m_es.Difficult = ;
- break;
- case "一般": m_es.Difficult = ;
- break;
- case "难": m_es.Difficult = ;
- break;
- }
- m_es.AnswerNote = Convert.ToString(dt.Rows[i][]);//答案解析
- m_es.GroupID = Convert.ToInt32(ParentRowID);
- b_examsubject.Insert(m_es);
- #endregion
- //插入主观题答案
- if ((type == "填空") || (type == "简答"))
- {
- m_es.SubjectGuid = m_es.SubjectGuid;
- m_es.RightAnswer = Convert.ToString(dt.Rows[i][]);//正确答案
- b_examsubject.Update(m_es);
- }
- //插入客观题答案
- else
- {
- //for (int j = 3; j < 7; j++)
- //{
- // m_ea.SubjectGuid = m_es.SubjectGuid;
- // m_ea.AnswerGuid = Guid.NewGuid().ToString();
- // m_ea.AnswerName = Convert.ToString(dt.Rows[i][j]);//答案
- // b_examanswer.Insert(m_ea);
- //}
- DataView dvRecord = dt.DefaultView;
- string answerid1 = Guid.NewGuid().ToString();
- string answerid2 = Guid.NewGuid().ToString();
- string answerid3 = Guid.NewGuid().ToString();
- string answerid4 = Guid.NewGuid().ToString();
- string answerid5 = Guid.NewGuid().ToString();
- string answerid6 = Guid.NewGuid().ToString();
- if (Convert.ToString(dvRecord[i][]) != "")
- b_examanswer.InsertAnswer(answerid1, Convert.ToString(dvRecord[i][]), false, m_es.SubjectGuid);
- if (Convert.ToString(dvRecord[i][]) != "")
- b_examanswer.InsertAnswer(answerid2, Convert.ToString(dvRecord[i][]), false, m_es.SubjectGuid);
- if (Convert.ToString(dvRecord[i][]) != "")
- b_examanswer.InsertAnswer(answerid3, Convert.ToString(dvRecord[i][]), false, m_es.SubjectGuid);
- if (Convert.ToString(dvRecord[i][]) != "")
- b_examanswer.InsertAnswer(answerid4, Convert.ToString(dvRecord[i][]), false, m_es.SubjectGuid);
- if (Convert.ToString(dvRecord[i][]) != "")
- b_examanswer.InsertAnswer(answerid5, Convert.ToString(dvRecord[i][]), false, m_es.SubjectGuid);
- if (Convert.ToString(dvRecord[i][]) != "")
- b_examanswer.InsertAnswer(answerid6, Convert.ToString(dvRecord[i][]), false, m_es.SubjectGuid);
- //添加正确答案
- int num = ;
- if (Convert.ToString(dvRecord[i][]) != "")
- {
- string strright = Convert.ToString(dvRecord[i][]).Trim();
- if (strright.IndexOf('A') >= || strright.IndexOf('a') >= )
- {
- num++;
- b_examanswer.UpdateAnswer_isRight(answerid1, true);
- }
- if (strright.IndexOf('B') >= || strright.IndexOf('b') >= )
- {
- num++;
- b_examanswer.UpdateAnswer_isRight(answerid2, true);
- }
- if (strright.IndexOf('C') >= || strright.IndexOf('c') >= )
- {
- num++;
- b_examanswer.UpdateAnswer_isRight(answerid3, true);
- }
- if (strright.IndexOf('D') >= || strright.IndexOf('d') >= )
- {
- num++;
- b_examanswer.UpdateAnswer_isRight(answerid4, true);
- }
- if (strright.IndexOf('E') >= || strright.IndexOf('e') >= )
- {
- num++;
- b_examanswer.UpdateAnswer_isRight(answerid5, true);
- }
- if (strright.IndexOf('F') >= || strright.IndexOf('f') >= )
- {
- num++;
- b_examanswer.UpdateAnswer_isRight(answerid6, true);
- }
- }
- }
- }
- }
- }
- BindGrid();
- }
单表导入到一个DataGrid里面
后台代码
- protected void InfoExport()
- {
- try
- {
- string ExcelName = this.CreateExcel();
- //将服务器上的Excel导出
- // CuteWebUIOperate.DownloadFile(HttpContext.Current, Server.MapPath("ExcelExport/") + ExcelName, ExcelName, false);
- string strScript = "window.open('ExcelExport/" + ExcelName + "');";
- this.WriteAjaxMessage(strScript);
- }
- catch
- {
- throw;
- }
- }
- protected string CreateExcel() //生成Excel
- {
- string Header = "报名信息";
- string strFileName = "";
- // 生成文件夹
- string fileFolderPath = Server.MapPath("ExcelExport/");
- if (!System.IO.Directory.Exists(fileFolderPath))
- System.IO.Directory.CreateDirectory(fileFolderPath);
- Workbook wb = new Workbook();
- wb.Worksheets.Add("Sheet1");
- Worksheet ws = wb.ActiveWorksheet;
- //first row 19cell
- WorksheetMergedCellsRegionCollection wm = ws.MergedCellsRegions;
- WorksheetMergedCellsRegion wmc = wm.Add(, , , );//起始位置和终止位置
- wmc.Value = Header;
- wmc.CellFormat.Alignment = HorizontalCellAlignment.Center;
- wmc.CellFormat.Font.Bold = ExcelDefaultableBoolean.True;
- wmc.CellFormat.BottomBorderColor = Color.Black;
- wmc.CellFormat.LeftBorderColor = Color.Black;
- wmc.CellFormat.RightBorderColor = Color.Black;
- wmc.CellFormat.TopBorderColor = Color.Black;
- wmc.CellFormat.BottomBorderStyle = CellBorderLineStyle.Thin;
- wmc.CellFormat.LeftBorderStyle = CellBorderLineStyle.Thin;
- wmc.CellFormat.RightBorderStyle = CellBorderLineStyle.Thin;
- wmc.CellFormat.TopBorderStyle = CellBorderLineStyle.Thin;
- wmc.CellFormat.WrapText = ExcelDefaultableBoolean.True;
- wmc.CellFormat.Font.Name = "宋体";
- //字体大小
- wmc.CellFormat.Font.Height = ;
- IWorksheetCellFormat HeadCellFormat = wb.CreateNewWorksheetCellFormat();
- HeadCellFormat.Alignment = HorizontalCellAlignment.Center;
- HeadCellFormat.Font.Bold = ExcelDefaultableBoolean.True;
- HeadCellFormat.Font.Name = "宋体";
- HeadCellFormat.BottomBorderColor = Color.Black;
- HeadCellFormat.LeftBorderColor = Color.Black;
- HeadCellFormat.RightBorderColor = Color.Black;
- HeadCellFormat.TopBorderColor = Color.Black;
- HeadCellFormat.BottomBorderStyle = CellBorderLineStyle.Thin;
- HeadCellFormat.LeftBorderStyle = CellBorderLineStyle.Thin;
- HeadCellFormat.RightBorderStyle = CellBorderLineStyle.Thin;
- HeadCellFormat.TopBorderStyle = CellBorderLineStyle.Thin;
- HeadCellFormat.WrapText = ExcelDefaultableBoolean.True;
- IWorksheetCellFormat ItemCellFormat = wb.CreateNewWorksheetCellFormat();
- //CellFormat.Alignment = HorizontalCellAlignment.Center;
- //CellFormat.Font.Bold = ExcelDefaultableBoolean.True;
- ItemCellFormat.FillPattern = FillPatternStyle.Default;
- ItemCellFormat.ShrinkToFit = ExcelDefaultableBoolean.True;
- ItemCellFormat.BottomBorderColor = Color.Black;
- ItemCellFormat.LeftBorderColor = Color.Black;
- ItemCellFormat.RightBorderColor = Color.Black;
- ItemCellFormat.TopBorderColor = Color.Black;
- ItemCellFormat.BottomBorderStyle = CellBorderLineStyle.Thin;
- ItemCellFormat.LeftBorderStyle = CellBorderLineStyle.Thin;
- ItemCellFormat.RightBorderStyle = CellBorderLineStyle.Thin;
- ItemCellFormat.TopBorderStyle = CellBorderLineStyle.Thin;
- ItemCellFormat.WrapText = ExcelDefaultableBoolean.True;
- ItemCellFormat.FormatString = "##,##0.00";
- ItemCellFormat.Font.Name = "宋体";
- int n;
- n = ;
- wmc = wm.Add(, n, , n++);
- wmc.Value = "序号";
- wmc.CellFormat.SetFormatting(HeadCellFormat);
- wmc = wm.Add(, n, , n++);
- wmc.Value = "姓名";
- wmc.CellFormat.SetFormatting(HeadCellFormat);
- wmc = wm.Add(, n, , n++);
- wmc.Value = "身份证号";
- wmc.CellFormat.SetFormatting(HeadCellFormat);
- wmc = wm.Add(, n, , n++);
- wmc.Value = "单位名称";
- wmc.CellFormat.SetFormatting(HeadCellFormat);
- wmc = wm.Add(, n, , n++);
- wmc.Value = "计划名称";
- wmc.CellFormat.SetFormatting(HeadCellFormat);
- wmc = wm.Add(, n, , n++);
- wmc.Value = "报名项";
- wmc.CellFormat.SetFormatting(HeadCellFormat);
- wmc = wm.Add(, n, , n++);
- wmc.Value = "准考证号";
- wmc.CellFormat.SetFormatting(HeadCellFormat);
- wmc = wm.Add(, n, , n++);
- wmc.Value = "成绩";
- wmc.CellFormat.SetFormatting(HeadCellFormat);
- ws.Columns[n].Width = * ;
- wmc = wm.Add(, n, , n++);
- wmc.Value = "是否合格";
- wmc.CellFormat.SetFormatting(HeadCellFormat);
- DataView dv = GetExcelData();//获取报名信息
- for (int i = ; i < dv.Count; i++)
- {
- n = ;
- wmc = wm.Add(i + , n, i + , n++);
- wmc.Value = Convert.ToString(i + );
- wmc.CellFormat.SetFormatting(ItemCellFormat);
- wmc = wm.Add(i + , n, i + , n++);
- wmc.Value = dv[i]["Name"].ToString();
- wmc.CellFormat.SetFormatting(ItemCellFormat);
- wmc = wm.Add(i + , n, i + , n++);
- wmc.Value = dv[i]["IdentityNum"].ToString();
- wmc.CellFormat.SetFormatting(ItemCellFormat);
- wmc = wm.Add(i + , n, i + , n++);
- wmc.Value = dv[i]["DanWeiName"].ToString();
- wmc.CellFormat.SetFormatting(ItemCellFormat);
- wmc = wm.Add(i + , n, i + , n++);
- wmc.Value = dv[i]["PlanName"].ToString();
- wmc.CellFormat.SetFormatting(ItemCellFormat);
- wmc = wm.Add(i + , n, i + , n++);
- wmc.Value = dv[i]["ItemName"].ToString();
- wmc.CellFormat.SetFormatting(ItemCellFormat);
- wmc = wm.Add(i + , n, i + , n++);
- wmc.Value = dv[i]["ZhunKZNum"].ToString();
- wmc.CellFormat.SetFormatting(ItemCellFormat);
- wmc = wm.Add(i + , n, i + , n++);
- wmc.Value = dv[i]["Score"].ToString();
- wmc.CellFormat.SetFormatting(ItemCellFormat);
- wmc = wm.Add(i + , n, i + , n++);
- wmc.Value = dv[i]["IsPass"].ToString();
- wmc.CellFormat.SetFormatting(ItemCellFormat);
- }
- string mark = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString();
- strFileName = "Export_" + mark + ".xls";
- BIFF8Writer.WriteWorkbookToFile(wb, Server.MapPath("ExcelExport/" + strFileName));
- return strFileName;
- }
- protected DataView GetExcelData()
- {
- int TotalNum = ;
- string where = " where 1=1 ";
- if (!String.IsNullOrEmpty(txtIdentityNum.Text))
- {
- where += "and IdentityNum like '%" + txtIdentityNum.Text + "%'";
- }
- where += "and PlanGuid = '" + PlanGuid + "'";
- where += "and Status != '" + + "'";
- string connectionStringName = "DJG_PeiXun_ConnectionString";
- string fields = "*";
- string sortExpression = "order by Row_ID desc";
- DataTable DvPaging = new DB_Common().GetData_Page_Table(
- fields,
- DataGrid1.PageSize,
- DataGrid1.CurrentPageIndex + ,
- "View_Score_UserType",
- "Row_ID",
- where,
- sortExpression,
- out TotalNum,
- connectionStringName
- );
- return DvPaging.DefaultView;
- }
C# Excel导入的更多相关文章
- C# Excel导入、导出【源码下载】
本篇主要介绍C#的Excel导入.导出. 目录 1. 介绍:描述第三方类库NPOI以及Excel结构 2. Excel导入:介绍C#如何调用NPOI进行Excel导入,包含:流程图.NOPI以及C#代 ...
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(63)-Excel导入和导出-自定义表模导入
系列目录 前言 上一节使用了LinqToExcel和CloseXML对Excel表进行导入和导出的简单操作,大家可以跳转到上一节查看: ASP.NET MVC5+EF6+EasyUI 后台管理系统(6 ...
- 解析大型.NET ERP系统 设计通用Microsoft Excel导入功能
做企业管理软件很难避免与Microsoft Excel打交道,常常是软件做好了,客户要求说再做一个Excel导入功能.导入Excel数据的功能的难度不大,从Excel列数据栏位的取值,验证值,再导入到 ...
- (转)高效的将excel导入sqlserver中
大部分人都知道用oledb来读取数据到dataset,但是读取之后怎么处理dataset就千奇百怪了.很多人通过循环来拼接sql,这样做不但容易出错而且效率低下,System.Data.SqlClie ...
- 安全的将excel导入sqlite3的解决方案
最近在做一个小项目时,需要把一个excel中的数据保存到sqlite3数据库中以备后用,表中有字符也有数字,要用到特定的数据类型方便后续使用,参照网上的方法,将excel文件转换为csv文件后,在导入 ...
- 利用反射实现通用的excel导入导出
如果一个项目中存在多种信息的导入导出,为了简化代码,就需要用反射实现通用的excel导入导出 实例代码如下: 1.创建一个 Book类,并编写set和get方法 package com.bean; p ...
- C# EXCEL导入 混合列文字为空,找不到可安装的 ISAM的解决办法
C# EXCEL导入 混合列文字为空,找不到可安装的 ISAM的解决办法 使用C#导入 Excel数据到 DataTable,如果连接串中只写 Excel 8.0,则正常的字符列,数值列都没有问题,但 ...
- Excel导入导出的业务进化场景及组件化的设计方案(上)
1:前言 看过我文章的网友们都知道,通常前言都是我用来打酱油扯点闲情的. 自从写了上面一篇文章之后,领导就找我谈话了,怕我有什么想不开. 所以上一篇的(下)篇,目前先不出来了,哪天我异地二次回忆的时候 ...
- Excel 导入到Datatable 中,再使用常规方法写入数据库
首先呢?要看你的电脑的office版本,我的是office 2013 .为了使用oledb程序,需要安装一个引擎.名字为AccessDatabaseEngine.exe.这里不过多介绍了哦.它的数据库 ...
- nopi excel 导入
#region 从Excel导入 /// <summary> /// 读取excel ,默认第一行为标头 /// </summary> /// <param name=& ...
随机推荐
- Unity3D之协程(Coroutines & Yield )
在Unity中StartCoroutine/yield return这个模式到底是怎么应用的? 比如你要一个方法进行一个比较耗时的复杂运算~同时又想让脚本流畅的进行其他操作而不是卡在那里等该方法执行完 ...
- SQL Prompt自定义代码片段
新增代码片段: 代码片段管理: 代码片段中可以使用以下占位符:详见参考: $DATE$ 插入当前日期. $TIME$ 插入当前时间 $USER$ 插入当前电脑的用户名 $PASTE$ 插入剪切板内容 ...
- loadrunner常用术语
1.场景 在loadrunner中主要表现为controller中设计与执行测试用例中的用户场景.主要工作有,在controller中选择虚拟用户脚本.设置虚拟用户数量.配置虚拟用户运行时的行为.选择 ...
- awk命令简单介绍
简介 awk是一个强大的文本分析工具,相对于grep的查找,sed的编辑,awk在其对数据分析并生成报告时,显得尤为强大.简单来说awk就是把文件逐行的读入,以空格为默认分隔符将每行切片,切开的部分再 ...
- 19 Using Optimizer Hints
19.1 Overview of Optimizer Hints A hint is an instruction to the optimizer. In a test or development ...
- 匿名函数和Lamda
不是本人所写!网络收集 C#中的匿名函数和Lamda是很有意思的东东,那么我们就来介绍一下,这到底是什么玩意,有什么用途了? 打开visual studio 新建一个控制台程序. 我们利用委托来写一个 ...
- Postman 安装及使用入门教程
安装 本文只是基于 Chrome 浏览器的扩展插件来进行的安装,并非单独应用程序. 首先,你要台电脑,其次,安装有 Chrome 浏览器,那你接着往下看吧. 1. 官网安装(别看) 打开官网,http ...
- C#_批量插入数据到Sqlserver中的四种方式
先创建一个用来测试的数据库和表,为了让插入数据更快,表中主键采用的是GUID,表中没有创建任何索引.GUID必然是比自增长要快的,因为你生成一个GUID算法所花的时间肯定比你从数据表中重新查询上一条记 ...
- News common vocabulary
英语新闻常用词汇与短语 经济篇 accumulated deficit 累计赤字 active trade balance 贸易顺差 adverse trade balance 贸易逆差 aid 援助 ...
- iOS7中的ViewController切换
转自:https://onevcat.com/2013/10/vc-transition-in-ios7/ iOS 7 SDK之前的VC切换解决方案 在深入iOS 7的VC切换效果的新API实现之前, ...