將Exce表中的數(shù)據(jù)導(dǎo)入到數(shù)據(jù)庫(kù)中
我們程序員有些時(shí)候會(huì)有將客戶(hù)表中的數(shù)據(jù)導(dǎo)入到項(xiàng)目的表中的需求,用來(lái)做數(shù)據(jù)基礎(chǔ),那么就要一些小技巧,本文就做過(guò)的一些實(shí)例出發(fā)談一談。
-
首先頁(yè)面上的按鈕
<td >
<input id="Fileexcle" type="file" runat="server" class="fileword" />
<asp:Button ID="fileUpload" runat="server" Text="導(dǎo)入數(shù)據(jù)" OnClick="fileUpload_Click"/>請(qǐng)選擇Excle文件上傳,注意格式(.xls/.xlsx)</td>
創(chuàng)建一個(gè)按鈕,申明只識(shí)別的文件格式
-
后天頁(yè)面
以上按鈕為例:
創(chuàng)建onclick事件:
protected void fileUpload_Click(object sender, EventArgs e)
{
if (Fileexcle.PostedFile.FileName == "")//獲取文件名稱(chēng)
{
JscriptPrint("請(qǐng)選擇要上傳的Excel文件!", "list.aspx", "Error");
return;
}
string fileName = Fileexcle.PostedFile.FileName;
int extendNameIndex = fileName.LastIndexOf(".");
string extendName = fileName.Substring(extendNameIndex);
//驗(yàn)證是否為Exel格式
if (extendName.ToLower() == ".xls" || extendName.ToLower() == ".xlsx")
{
result = upload(Fileexcle);//upload方法是獲取文件路徑的
if (result.Length != 0)
{
InsertData();//將Excel表中的數(shù)據(jù)導(dǎo)入到表中方法
DateBind();
}
else
{
JscriptPrint("上傳失?。?, "ImportTest.aspx", "Error");
}
}
else
{
JscriptPrint("請(qǐng)選擇正確的Excel文件(.xls/.xlsx)!", "ImportTest.aspx", "Error");
return;
}
}
Upload方法
/// <summary>
/// 獲取上傳文件路徑
/// </summary>
/// <param name="uploadFiles">上傳文件的控件名稱(chēng)</param>
/// <returns>返回路徑</returns>
public string upload(System.Web.UI.HtmlControls.HtmlInputFile uploadFiles)
{
string fileName = uploadFiles.PostedFile.FileName;
int extendNameIndex = fileName.LastIndexOf(".");
string extendName = fileName.Substring(extendNameIndex + 1);
string newName = DateTime.Now.ToString("yyyyMMddHHmmss");
string path = "0";
try
{
newName += uploadFiles.PostedFile.ContentLength.ToString();
path = System.Web.HttpContext.Current.Server.MapPath("~/upload/excel/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path += "¥¥" + newName + "." + extendName;
uploadFiles.PostedFile.SaveAs(path);
}
catch
{
return "0";
}
return path;
}
InsertData方法
private void InsertData()
{
list = getList();//首先獲取數(shù)據(jù)源
if (list.Count() > 0)
{
int i = 0, j = 0;
using (Entities db = new Entities())
{
string s = "";
foreach (var li in list)//遍歷集合
{
S_ServiceFee donate = new S_ServiceFee();
donate.SDepartMent = li.SDepartMent;
donate.SName = li.SName;
donate.SEducation = li.SEducation;
donate.Station = li.Station;
db.S_ServiceFee.Add(donate);
i += 1;
j += 1;
db.SaveChanges();
}
s += "本次成功導(dǎo)入" + i + "條數(shù)據(jù),總條數(shù)為:" + list.Count();
JscriptPrint(s + "操作成功!", "ImportTest.aspx", "Success");
}
}
}
getList()方法
protected List<data> getList()
{
List<data> list = new List<data>();//申明集合數(shù)據(jù)類(lèi)型
Cells cells;
Workbook workbook = new Workbook();
try
{
workbook.Open(result);
}
catch (ArgumentOutOfRangeException ex)
{
// Response.Write(ex.ToString());
}
cells = workbook.Worksheets[0].Cells;
PropertyInfo[] ps = typeof(data).GetProperties();
if (cells.MaxDataColumn + 1 < ps.Count() - 2)
{
JscriptPrint("模板讀取有誤" + "實(shí)際字段數(shù)為:" + (cells.MaxDataColumn + 1) + ",正確字段數(shù)應(yīng)為:" + (ps.Count() - 2), "", "Error");
return list;
}
string s = "";
for (int i = 1; i < cells.MaxDataRow + 1; i += 1)//表中的行數(shù),從第二行開(kāi)始,考慮到第一行是表頭數(shù)據(jù)
{
data d = new data();
d.sort = i + 1;
for (int j = 0; j < cells.MaxDataColumn + 1; j += 1)//表中的列數(shù)
{
s = cells[i, j].StringValue.Trim();//獲取列行對(duì)應(yīng)的數(shù)據(jù)
//一行行的讀取數(shù)據(jù),插入數(shù)據(jù)庫(kù)的代碼也可以在這里寫(xiě)
switch (j)
{
case 0:
d.SDepartMent = s;//表示導(dǎo)入表中的第二行第一列中的數(shù)據(jù)
break;
case 1:
d.SName = s;
break;
case 2:
d.SEducation = s;
break;
case 3:
d.Station = s;
break;
case 4:
d.PayStation = s;
break;
case 5:
d.PayFuD = s;
Break;
default:
break;
}
}
list.Add(d);
}
return list;
}
上面data類(lèi)
public class data
{
public string SId { get; set; }
public string SDepartMent { get; set; }
public string SName { get; set; }
public string SEducation { get; set; }
public string JiDJx { get; set; }
public int sort { get; set; }
}
-
總結(jié)
總體思想:首先數(shù)據(jù)源獲?。ㄒ獙?dǎo)入的表格數(shù)據(jù)),再將它讀取并存儲(chǔ)到臨時(shí)的集合中,最后遍歷集合,將它付給你new的新對(duì)象保存。
本人初級(jí)程序員,如有錯(cuò)誤,請(qǐng)指出,再者有更高明的做法,歡迎討論。