用户经常会有这种需求,可以将excel中的数据自动导入到数据库,而不用费时费力地手动添加,或者将某些数据导出存放到excel表格中。
一、excel导入
实现思路:先将excel文件上传到服务器(文件上传请移步前一篇文章插件webuploader实现文件上传),然后读取表格中的内容,将内容添加到相应数据表中,最后再将上传的excel文件删除。
前台代码:
<div class="div-content">
<div class="list">
<dl>
<dt>Excel文件:</dt>
<dd>
<asp:TextBox ID="txtImgUrl" runat="server" CssClass="input normal upload-path" />
<div class="upload-box upload-img">
</div>
</dd>
</dl>
</div>
<div class="toolbar">
<asp:Button ID="btnOK" Style="margin-left: 20px" runat="server" Text="导入" class="btn" OnClick="btnOK_Click" />
</div>
</div>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
后台代码如下:
//导入事件
protected void btnOK_Click(object sender, EventArgs e)
{
DataTable dt = null;
if (this.txtImgUrl.Text.Trim() != "")
{
string filePath = MapPath(this.txtImgUrl.Text.Trim());//获取虚拟路径
FileStream file = File.OpenRead(filePath);//读取文件
dt = DotNet.FrameWork.Common.Office.NPOIExcelReader.RenderFromExcel(file);
if (dt.Rows.Count > 0)
{
if (dt.Rows.Count > 200)
{
JscriptMsg("导入记录数超过最大限制200条!请分批导入!", string.Empty);
return;
}
HR_Employee mdEmployee = new HR_Employee();
HR_UserProfile mdUserProfile;
HR_EmployeeManager bllEmployee = new HR_EmployeeManager();
departmentManager bllDept = new departmentManager();
HR_PostManager bllPost = new HR_PostManager();
HR_DutyManager bllDuty = new HR_DutyManager();
HR_UserProfileManager bllUserProfile = new HR_UserProfileManager();
HR_EnterpriseManager bllEnterprise = new HR_EnterpriseManager();
int sucCount = 0, errorCount = 0;
try
{
foreach (DataRow dr in dt.Rows)
{
mdUserProfile = new HR_UserProfile();
if (dr["身份证号"].ToString() == "" || bllEmployee.Exists(dr["身份证号"].ToString()))
{
errorCount++;
continue;
}
mdEmployee = new HR_Employee();
mdEmployee.UId = bllUserProfile.GetUIdByUPshenfenID(dr["身份证号"].ToString());
mdEmployee.dept_id = dr["部门"].ToString() == "" ? 0 : bllDept.GetDeptIdByDeptName(dr["部门"].ToString());
mdEmployee.PID = dr["岗位"].ToString() == "" ? 0 : bllPost.GetPIdByPostName(dr["岗位"].ToString());
mdEmployee.E_Id = dr["保险所在公司"].ToString() == "" ? 0 : bllEnterprise.EidByEname(dr["保险所在公司"].ToString());
mdEmployee.duty = dr["职位"].ToString() == "" ? 0 : bllDuty.GetIdByDutyName(dr["职位"].ToString());
mdEmployee.emp_name = dr["姓名"].ToString();
mdEmployee.emp_sex = dr["性别"].ToString();
mdEmployee.emp_CardId = dr["身份证号"].ToString();
mdEmployee.culture_degree = dr["文化程度"].ToString();
mdEmployee.political_status = dr["政治面貌"].ToString();
mdEmployee.emp_mobile = dr["联系方式"].ToString();
mdEmployee.related_man = dr["紧急人"].ToString();
mdEmployee.urgent_telephone = dr["紧急联系方式"].ToString();
mdEmployee.contract_beg_date = DataTimeOperate(dr["合同起始日期"].ToString()); //dr["合同起始日期"].ToString() == "" ? Convert.ToDateTime("1900-1-1") : Convert.ToDateTime(dr["合同起始日期"].ToString().Replace("/", "-"));
mdEmployee.contract_end_date = DataTimeOperate(dr["合同终止日期"].ToString()); //dr["合同终止日期"].ToString() == "" ? Convert.ToDateTime("1900-1-1") : Convert.ToDateTime(dr["合同终止日期"].ToString().Replace("/", "-"));
mdEmployee.contract_count = dr["合同期限"].ToString() == "" ? 0 : Convert.ToInt32(dr["合同期限"]);
mdEmployee.contract_period = dr["合同续订次数"].ToString() == "" ? 0 : Convert.ToInt32(dr["合同续订次数"]);
mdEmployee.note_info = dr["备注"].ToString();
mdEmployee.Earea = "";
mdEmployee.emp_email = "";
mdEmployee.emp_qq = "";
mdEmployee.emp_weixin = "";
mdEmployee.technical = "";
mdEmployee.emp_state = int.Parse(this.rblState.SelectedValue);
mdEmployee.myorder = 999;
int emp_id = bllEmployee.Add(mdEmployee);//添加到职工表
if (emp_id > 0)
{
sucCount++;
}
else
{
errorCount++;
}
}
}
catch (Exception ex)
{
errorCount++;
}
Response.Write("<script>top.dialog.get(window).close();</script>");
JscriptMsg("导入成功" + sucCount + "条,失败" + errorCount + "条", "EmployeeList.aspx");
}
else
{
JscriptMsg("请确保文档中有数据记录行!", string.Empty);
}
File.Delete(filePath);
}
else
{
JscriptMsg("请先选择要导入的Excel文档!", string.Empty);
}
}
//日期格式处理
protected DateTime DataTimeOperate(string str_date)
{
if (str_date != "")
{
int index = str_date.LastIndexOf("/");
string newdate = str_date.Substring(index + 1) + "/" + str_date.Substring(0, index);
return Convert.ToDateTime(newdate);
}
else
{
return Convert.ToDateTime("1900-1-1");
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
二、excel导出
用户自定义选择要导出的字段。
实现代码(前台使用CheckBoxList动态绑定所有字段)
<div class="div-content">
<div class="list">
<asp:CheckBoxList ID="cblist" runat="server" RepeatColumns="7" RepeatDirection="Horizontal">
</asp:CheckBoxList>
</div>
<div class="toolbar">
<asp:Button ID="btnOK" Style="margin-left: 20px" runat="server" Text="导出" class="btn" OnClick="btnOK_Click" />
</div>
</div>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
后台代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindField();
}
}
//绑定字段
protected void BindField()
{
this.cblist.Items.Clear();
this.cblist.Items.Add(new ListItem("部门", "b.dep_name as 部门"));
this.cblist.Items.Add(new ListItem("岗位", "c.PostName as 岗位"));
this.cblist.Items.Add(new ListItem("姓名", "a.emp_name as 姓名"));
this.cblist.Items.Add(new ListItem("出生日期", "convert(varchar(50),d.UPBirthday,23) as 出生日期"));
this.cblist.Items.Add(new ListItem("年龄", "datediff(year,d.UPBirthday,getdate()) as 年龄"));
this.cblist.Items.Add(new ListItem("性别", "a.emp_sex as 性别"));
this.cblist.Items.Add(new ListItem("身份证号", "a.emp_CardId as 身份证号"));
this.cblist.Items.Add(new ListItem("婚姻状况", "(case UPMarriage when 1 then '已婚' when 0 then '未婚' else null end)as 婚姻状况"));
this.cblist.Items.Add(new ListItem("入职时间", "convert(varchar(50),d.UPEntry,23) as 入职时间"));
this.cblist.Items.Add(new ListItem("转正时间", "convert(varchar(50),d.UPZhuanzhengDate,23) as 转正时间"));
this.cblist.Items.Add(new ListItem("工龄(月)", "datediff(month,d.UPEntry,getdate()) as '工龄(月)'"));
this.cblist.Items.Add(new ListItem("薪资", "d.USalary as 薪资"));
this.cblist.Items.Add(new ListItem("合同起始日期", "convert(varchar(50),a.contract_beg_date,23) as 合同起始日期"));
this.cblist.Items.Add(new ListItem("合同终止日期", "convert(varchar(50),a.contract_end_date,23) as 合同终止日期"));
this.cblist.Items.Add(new ListItem("工作经历", ""));
for (int i = 0; i < this.cblist.Items.Count; i++)
{
//if (i < 12)
cblist.Items[i].Selected = true;
}
}
//获取表格
protected DataTable BindTable(string chkSelect)
{
return bllEmplyee.GetListByMultiCond(chkSelect);
}
//开始导出
protected void btnOK_Click(object sender, EventArgs e)
{
try
{
string chkSelect = "";
for (int i = 0; i < cblist.Items.Count; i++)
{
if (cblist.Items[i].Selected)
{
chkSelect += cblist.Items[i].Value + ",";
}
}
if (chkSelect != "")
{
chkSelect = chkSelect.Substring(0, chkSelect.Length - 1);
}
DataTable dt = new DataTable();
if (this.cblist.Items[34].Selected && this.cblist.Items[34].Text == "工作经历")
{
dt = BindTable(chkSelect.Substring(0, chkSelect.Length - 1));
dt.Columns.Add("工作起止日期1", typeof(System.String));
dt.Columns.Add("工作情况1", typeof(System.String));
dt.Columns.Add("离职原因1", typeof(System.String));
dt.Columns.Add("工作起止日期2", typeof(System.String));
dt.Columns.Add("工作情况2", typeof(System.String));
dt.Columns.Add("离职原因2", typeof(System.String));
DataTable dtwork;
HR_UserWorkResumeManager bllUserWork = new HR_UserWorkResumeManager();
foreach (DataRow dr in dt.Rows)
{
dtwork = null;
dtwork = bllUserWork.GetListByEmpId(Convert.ToInt32(dr["emp_id"]));
if (dtwork.Rows.Count > 0)
{
dr["工作起止日期1"] = dtwork.Rows[0]["UWPeriod"];
dr["工作情况1"] = dtwork.Rows[0]["UWCompany"];
dr["离职原因1"] = dtwork.Rows[0]["UWLeaveReason"];
if (dtwork.Rows.Count > 1)
{
dr["工作起止日期2"] = dtwork.Rows[1]["UWPeriod"];
dr["工作情况2"] = dtwork.Rows[1]["UWCompany"];
dr["离职原因2"] = dtwork.Rows[1]["UWLeaveReason"];
}
}
}
}
else
dt = BindTable(chkSelect);
dt.Columns.Remove("new_index");
dt.Columns.Remove("dutyorder");
dt.Columns.Remove("myorder");
dt.Columns.Remove("UPEntry");
dt.Columns.Remove("emp_id");
DotNet.FrameWork.Common.Office.NPOIExcelReader.RenderToExcel(dt, Context, DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".xls");
Response.Write("<script>top.dialog.get(window).close();</script>");
}
catch { }
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
其中代码中所用方法DotNet.FrameWork.Common.Office.NPOIExcelReader.RenderFromExcel所在类请前往下载页面下载——NPOI调用接口