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=& ...
 
随机推荐
- phpstorm相关设置
			
1, phpstorm安装好后在编辑页随便点哪里都能把光标移过去,类似于word的“即点即输”.仔细找了下,终于找出来怎么关闭了: 这一功能在phpstorm中不知道叫啥名,去掉方法是 打开File- ...
 - aws在线技术峰会笔记-主会场
			
容器服务:Elastic container service IoT可以采用无服务器架构.
 - iOS - Frame  项目架构
			
前言 iOS 常见的几种架构: 标签式 Tab Menu 列表式 List Menu 抽屉式 Drawer 瀑布式 Waterfall 跳板式 Springborad 陈列馆式 Gallery 旋转木 ...
 - linux tar.gz
			
tar命令用于对文件打包压缩或解压,格式为:“tar [选项] [文件]”. 打包并压缩文件:“tar -czvf 压缩包名.tar.gz 文件名” 解压并展开压缩包:“tar -xzvf 压缩包名. ...
 - ERROR 1018 (HY000): Can't read dir of './test/' (errno: 13)
			
不能查看mysql中数据库的表. 一.查看 mysql> desc test; ERROR 1046 (3D000): No database selected mysql> use te ...
 - C语言中system()函数的用法总结(转)
			
system()函数功能强大,很多人用却对它的原理知之甚少先看linux版system函数的源码: #include <sys/types.h> #include <sys/wait ...
 - Python_Day2_基础2
			
python基础之数据类型与变量 一.变量 变量作用:保存状态(程序的运行本质是一系列状态的变化,变量的目的就是用来保存状态,变量值的变化就构成了程序运行的不同结果.) Age=10 ----> ...
 - [分享] 晒一晒我的Windows7_SP1封装母盘(多图,附部分工具),老鸟飘过~
			
[分享] 晒一晒我的Windows7_SP1封装母盘(多图,附部分工具),老鸟飘过~ 大宝贝1 发表于 2012-8-9 18:01:57 https://www.itsk.com/thread-20 ...
 - C++类的交叉引用
			
对于C++中,两个类中相互引用对方,当然只能是在指针的基础上,于是我们知道.也就是说在A类的有一个指针引用B类的成员函数或成员对象,而B类中又有一个指针来访问A中的成员函数或对象.这就是C++中类的交 ...
 - Gson手动序列化POJO(工具类)
			
gson2.7版本 只是简单的工具类(练习所用): package pojo; import javax.xml.bind.annotation.XmlSeeAlso; import com.goog ...