任务:使用asp.net把*.zip包中压缩好的相同式样的excel数据文件导入SQL SERVER2000.
任务:使用asp.net把*.zip包中压缩好的相同式样的excel数据文件导入SQL SERVER2000.
汗,我真不知道怎么组织这个篇文章,应该是很小儿科目的东西.再是我认为写出来对新手还是有点看看的价值的。那天同学偷懒找我给他做个小TASK,要求用把*.zip包中压缩好的相同式样的excel数据文件导入SQL SERVER2000.由于没有接触到excel方面的开发,我想当然的认为Sql Server 2000 的OPENDATASOURCE + Jet OLE DB 提供程序即可完成任务,经过N次的尝试,錯誤N次。直到我把用来测试的excel文件打开之后,准备另存为时才发现其是以"文本文件(制表符分割)"保存的!此才豁然开朗,把測試用excel数据文件直接重命名为.TXT文件,使用BULK INSERT语句解决!
首先,我把此excel文件另存为excel工作簿文档,使用以下代码来获得它的表结构:
获得表结构代码
1SELECT * into xk_customer
2FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
3 'Data Source="c:\my.xls";Extended properties=Excel 8.0')[my$]
4
1SELECT * into xk_customer
2FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
3 'Data Source="c:\my.xls";Extended properties=Excel 8.0')[my$]
4
再手工给xk_customer表添加一個标识字段。
接着,我创建了用于导入数据的存储过程如下:
数据导入存储过程
1CREATE Proc xk_ImportData
2(
3@path nvarchar(2000)
4)
5AS
6---------参数说明:要导入的数据文件的路径------
7
8CREATE TABLE [##Import3] (
9 [MAC地址] [nvarchar] (255) COLLATE Chinese_PRC_CI_AS NULL ,
10 [短号] [nvarchar] (255) COLLATE Chinese_PRC_CI_AS NULL ,
11 [主叫号码] [nvarchar] (255) COLLATE Chinese_PRC_CI_AS NULL ,
12 [被叫号码] [nvarchar] (255) COLLATE Chinese_PRC_CI_AS NULL ,
13 [开始时间] [nvarchar] (255) COLLATE Chinese_PRC_CI_AS NULL ,
14 [时长] [nvarchar] (255) COLLATE Chinese_PRC_CI_AS NULL ,
15 [费率] [float] NULL ,
16 [费用] [float] NULL ,
17 [客户] [nvarchar] (255) COLLATE Chinese_PRC_CI_AS NULL ,
18 [通话类型] [nvarchar] (255) COLLATE Chinese_PRC_CI_AS NULL
19) ON [PRIMARY]
20
21
22DECLARE @sql varchar(5000)
23--Set @temp='c:\aaa.txt'
24Set @sql='BULK INSERT ##Import3'+
25 ' FROM '+''''+ @path+''''+'
26 WITH
27 (
28 FIELDTERMINATOR = '+''''+'\t'+''''+','+
29 'ROWTERMINATOR = '+''''+'\n'+''''+
30 ' )'
31--print @sql
32EXEC (@sql)
33
34INSERT INTO [xk_customer]([MAC地址], [短号], [主叫号码], [被叫号码], [开始时间], [时长], [费率], [费用], [客户], [通话类型])
35SELECT [MAC地址], [短号], [主叫号码], [被叫号码], [开始时间], [时长], [费率], [费用], [客户], [通话类型]
36FROM ##Import3 WHERE 客户<>'' AND MAC地址<>'' ORDER BY 开始时间
37Drop table ##Import3
38
39
40
1CREATE Proc xk_ImportData
2(
3@path nvarchar(2000)
4)
5AS
6---------参数说明:要导入的数据文件的路径------
7
8CREATE TABLE [##Import3] (
9 [MAC地址] [nvarchar] (255) COLLATE Chinese_PRC_CI_AS NULL ,
10 [短号] [nvarchar] (255) COLLATE Chinese_PRC_CI_AS NULL ,
11 [主叫号码] [nvarchar] (255) COLLATE Chinese_PRC_CI_AS NULL ,
12 [被叫号码] [nvarchar] (255) COLLATE Chinese_PRC_CI_AS NULL ,
13 [开始时间] [nvarchar] (255) COLLATE Chinese_PRC_CI_AS NULL ,
14 [时长] [nvarchar] (255) COLLATE Chinese_PRC_CI_AS NULL ,
15 [费率] [float] NULL ,
16 [费用] [float] NULL ,
17 [客户] [nvarchar] (255) COLLATE Chinese_PRC_CI_AS NULL ,
18 [通话类型] [nvarchar] (255) COLLATE Chinese_PRC_CI_AS NULL
19) ON [PRIMARY]
20
21
22DECLARE @sql varchar(5000)
23--Set @temp='c:\aaa.txt'
24Set @sql='BULK INSERT ##Import3'+
25 ' FROM '+''''+ @path+''''+'
26 WITH
27 (
28 FIELDTERMINATOR = '+''''+'\t'+''''+','+
29 'ROWTERMINATOR = '+''''+'\n'+''''+
30 ' )'
31--print @sql
32EXEC (@sql)
33
34INSERT INTO [xk_customer]([MAC地址], [短号], [主叫号码], [被叫号码], [开始时间], [时长], [费率], [费用], [客户], [通话类型])
35SELECT [MAC地址], [短号], [主叫号码], [被叫号码], [开始时间], [时长], [费率], [费用], [客户], [通话类型]
36FROM ##Import3 WHERE 客户<>'' AND MAC地址<>'' ORDER BY 开始时间
37Drop table ##Import3
38
39
40
任务完成了一半,接下来是使用ASP.NET做的一个前台程序了,其下的JavaScript的代码使inputFile的path不為空的時候,方使UpLoad-Button可用!·。
HTML页代码
1<form id="Form1" method="post" runat="server">
2 <INPUT id="txtFileName" type="file" name="txtFileName" onchange="enable_buttons()" runat="server">
3 <asp:button id="btnUpload" runat="server" Text="上传" Width="56px"></asp:button>
4 <asp:button id="btnCancel" runat="server" Text="取消" Width="56px"></asp:button>
5 <script language="javascript">
6this.onload = setfocus;
7function setfocus()
8{
9 document.getElementById("btnUpload").style.display="none";
10 document.getElementById("btnCancel").style.display="none";
11}
12function enable_buttons()
13{
14 document.getElementById("btnUpload").style.display="";
15 document.getElementById("btnCancel").style.display="";
16}
17 </script>
18 </form>
关于主要的功能类,还是要说明一下的,其实现了zip包的解压、文件的上传、和数据库操作。解压组件使用了开源的SharpZipLib。代码入下:
1<form id="Form1" method="post" runat="server">
2 <INPUT id="txtFileName" type="file" name="txtFileName" onchange="enable_buttons()" runat="server">
3 <asp:button id="btnUpload" runat="server" Text="上传" Width="56px"></asp:button>
4 <asp:button id="btnCancel" runat="server" Text="取消" Width="56px"></asp:button>
5 <script language="javascript">
6this.onload = setfocus;
7function setfocus()
8{
9 document.getElementById("btnUpload").style.display="none";
10 document.getElementById("btnCancel").style.display="none";
11}
12function enable_buttons()
13{
14 document.getElementById("btnUpload").style.display="";
15 document.getElementById("btnCancel").style.display="";
16}
17 </script>
18 </form>
主要功能类
1using System;
2using System.Text;
3using System.Collections;
4using System.IO;
5using System.Diagnostics;
6using System.Runtime.Serialization.Formatters.Binary;
7using System.Data;
8
9using ICSharpCode.SharpZipLib.BZip2;
10using ICSharpCode.SharpZipLib.Zip;
11using ICSharpCode.SharpZipLib.Zip.Compression;
12using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
13using ICSharpCode.SharpZipLib.GZip;
14
15namespace XingKeNetWork.Components
16{
17 /**//// <summary>
18 /// Tool 的摘要说明。
19 /// </summary>
20 public class Tool
21 {
22 public Tool()
23 {
24 //
25 // TODO: 在此处添加构造函数逻辑
26 //
27 }
28
29 /**//// <summary>
30 /// 文件解压函数
31 /// </summary>
32 /// <param name="stream">上传的文件流</param>
33 /// <param name="mFileName">返回文件名称</param>
34 /// <param name="sSavePath">文件保存路径</param>
35 private static void UnZipFile(Stream stream,out string mFileName,string sSavePath)
36 {
37 ZipInputStream s = new ZipInputStream(stream);
38 string temp="";
39
40 ZipEntry theEntry;
41 while ((theEntry = s.GetNextEntry()) != null)
42 {
43
44 //Console.WriteLine(theEntry.Name);
45
46 string directoryName = Path.GetDirectoryName(theEntry.Name);
47 string fileName = Path.GetFileName(theEntry.Name);
48 temp=Path.GetFileNameWithoutExtension(theEntry.Name)+".txt"; //使Excel文件另存为Text格式的文件,返回问文件名
49
50 // create directory
51 Directory.CreateDirectory(directoryName);
52
53 if (fileName != String.Empty)
54 {
55 //Path.GetFileNameWithoutExtension
56 //FileStream streamWriter = File.Create(theEntry.Name);
57 if (System.IO.File.Exists(sSavePath+temp))
58 {
59 File.Delete(sSavePath+temp);
60 }
61 FileStream streamWriter = File.Create(sSavePath+temp);//创建文件
62 //FileStream streamWriter = File.Create(@"C:\TempFiles\"+temp);
63
64 int size = 2048;
65 byte[] data = new byte[2048];
66 while (true)
67 {
68 size = s.Read(data, 0, data.Length);
69 if (size > 0)
70 {
71 streamWriter.Write(data, 0, size);
72 }
73 else
74 {
75 break;
76 }
77 }
78
79 streamWriter.Close();
80 }
81 }
82 mFileName=temp;
83 s.Close();
84
85 }
86
87
88 /**//// <summary>
89 /// 文件上传,支持多文件上传
90 /// </summary>
91 /// <param name="sSavePath">保持路径</param>
92 /// <returns>返回文件的路径集合</returns>
93 public static ArrayList UpLoad_FileAttachment(string sSavePath)
94 {
95 ArrayList array=new ArrayList();;
96 System.Web.HttpFileCollection myFiles=System.Web.HttpContext.Current.Request.Files;
97 System.Web.HttpPostedFile myPostedFile;
98 for (int i=0;i<=myFiles.Count-1;i++)
99 {
100 string temp;
101 myPostedFile=myFiles[i];
102 int nFileLen = myPostedFile.ContentLength;
103 if (nFileLen != 0)
104 {
105 UnZipFile(myPostedFile.InputStream,out temp,sSavePath);
106 array.Add(temp);
107 }
108 }
109 return array;
110 }
111
112 /**//// <summary>
113 /// 导入数据库
114 /// </summary>
115 /// <param name="path">要导入的文件路径</param>
116 /// <returns>受影响行数</returns>
117 public static int InsertToData(string path)
118 {
119 Database data=new Database();
120 System.Data.SqlClient.SqlParameter[] param={
121 data.MakeInParam("@path",SqlDbType.NVarChar,2000,path)
122 };
123 int i=data.RunProc("xk_ImportData",param,1);
124 return i;
125 }
126 }
127}
1using System;
2using System.Text;
3using System.Collections;
4using System.IO;
5using System.Diagnostics;
6using System.Runtime.Serialization.Formatters.Binary;
7using System.Data;
8
9using ICSharpCode.SharpZipLib.BZip2;
10using ICSharpCode.SharpZipLib.Zip;
11using ICSharpCode.SharpZipLib.Zip.Compression;
12using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
13using ICSharpCode.SharpZipLib.GZip;
14
15namespace XingKeNetWork.Components
16{
17 /**//// <summary>
18 /// Tool 的摘要说明。
19 /// </summary>
20 public class Tool
21 {
22 public Tool()
23 {
24 //
25 // TODO: 在此处添加构造函数逻辑
26 //
27 }
28
29 /**//// <summary>
30 /// 文件解压函数
31 /// </summary>
32 /// <param name="stream">上传的文件流</param>
33 /// <param name="mFileName">返回文件名称</param>
34 /// <param name="sSavePath">文件保存路径</param>
35 private static void UnZipFile(Stream stream,out string mFileName,string sSavePath)
36 {
37 ZipInputStream s = new ZipInputStream(stream);
38 string temp="";
39
40 ZipEntry theEntry;
41 while ((theEntry = s.GetNextEntry()) != null)
42 {
43
44 //Console.WriteLine(theEntry.Name);
45
46 string directoryName = Path.GetDirectoryName(theEntry.Name);
47 string fileName = Path.GetFileName(theEntry.Name);
48 temp=Path.GetFileNameWithoutExtension(theEntry.Name)+".txt"; //使Excel文件另存为Text格式的文件,返回问文件名
49
50 // create directory
51 Directory.CreateDirectory(directoryName);
52
53 if (fileName != String.Empty)
54 {
55 //Path.GetFileNameWithoutExtension
56 //FileStream streamWriter = File.Create(theEntry.Name);
57 if (System.IO.File.Exists(sSavePath+temp))
58 {
59 File.Delete(sSavePath+temp);
60 }
61 FileStream streamWriter = File.Create(sSavePath+temp);//创建文件
62 //FileStream streamWriter = File.Create(@"C:\TempFiles\"+temp);
63
64 int size = 2048;
65 byte[] data = new byte[2048];
66 while (true)
67 {
68 size = s.Read(data, 0, data.Length);
69 if (size > 0)
70 {
71 streamWriter.Write(data, 0, size);
72 }
73 else
74 {
75 break;
76 }
77 }
78
79 streamWriter.Close();
80 }
81 }
82 mFileName=temp;
83 s.Close();
84
85 }
86
87
88 /**//// <summary>
89 /// 文件上传,支持多文件上传
90 /// </summary>
91 /// <param name="sSavePath">保持路径</param>
92 /// <returns>返回文件的路径集合</returns>
93 public static ArrayList UpLoad_FileAttachment(string sSavePath)
94 {
95 ArrayList array=new ArrayList();;
96 System.Web.HttpFileCollection myFiles=System.Web.HttpContext.Current.Request.Files;
97 System.Web.HttpPostedFile myPostedFile;
98 for (int i=0;i<=myFiles.Count-1;i++)
99 {
100 string temp;
101 myPostedFile=myFiles[i];
102 int nFileLen = myPostedFile.ContentLength;
103 if (nFileLen != 0)
104 {
105 UnZipFile(myPostedFile.InputStream,out temp,sSavePath);
106 array.Add(temp);
107 }
108 }
109 return array;
110 }
111
112 /**//// <summary>
113 /// 导入数据库
114 /// </summary>
115 /// <param name="path">要导入的文件路径</param>
116 /// <returns>受影响行数</returns>
117 public static int InsertToData(string path)
118 {
119 Database data=new Database();
120 System.Data.SqlClient.SqlParameter[] param={
121 data.MakeInParam("@path",SqlDbType.NVarChar,2000,path)
122 };
123 int i=data.RunProc("xk_ImportData",param,1);
124 return i;
125 }
126 }
127}
完整的演示代码:下载!