1 把Excel文件当做一个数据源来进行数据的读取操作,实例如下:
2 01.public DataSet ExcelToDS(string Path)
3 02.{
4 03. string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;";
5 04. OleDbConnection conn = new OleDbConnection(strConn);
6 05. conn.Open();
7 06. string strExcel = "";
8 07. OleDbDataAdapter myCommand = null;
9 08. DataSet ds = null;
10 09. strExcel="select * from [sheet1$]";
11 10. myCommand = new OleDbDataAdapter(strExcel, strConn);
12 11. ds = new DataSet();
13 12. myCommand.Fill(ds,"table1");
14 13. return ds;
15 14.}
16
17 对于Excel中的表即sheet([sheet1$])如果不是固定的可以使用下面的方法得到
18 01.string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;";
19 02.OleDbConnection conn = new OleDbConnection(strConn);
20 03.DataTable schemaTable = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables,null);
21 04.string tableName=schemaTable.Rows[0][2].ToString().Trim();
22
23
24 另外:也可进行写入Excel文件,实例如下:
25 01.public void DSToExcel(string Path,DataSet oldds)
26 02.{
27 03. //先得到汇总Excel的DataSet 主要目的是获得Excel在DataSet中的结构
28 04. string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source ="+path1+";Extended Properties=Excel 8.0" ;
29 05. OleDbConnection myConn = new OleDbConnection(strCon) ;
30 06. string strCom="select * from [Sheet1$]";
31 07. myConn.Open ( ) ;
32 08. OleDbDataAdapter myCommand = new OleDbDataAdapter ( strCom, myConn ) ;
33 09. system.Data.OleDb.OleDbCommandBuilder builder=new OleDbCommandBuilder(myCommand);
34 10. //QuotePrefix和QuoteSuffix主要是对builder生成InsertComment命令时使用。
35 11. builder.QuotePrefix="["; //获取insert语句中保留字符(起始位置)
36 12. builder.QuoteSuffix="]"; //获取insert语句中保留字符(结束位置)
37 13. DataSet newds=new DataSet();
38 14. myCommand.Fill(newds ,"Table1") ;
39 15. for(int i=0;i<oldds.Tables[0].Rows.Count;i++)
40 16. {
41 17. //在这里不能使用ImportRow方法将一行导入到news中,
42 18. //因为ImportRow将保留原来DataRow的所有设置(DataRowState状态不变)。
43 19. //在使用ImportRow后newds内有值,但不能更新到Excel中因为所有导入行的DataRowState!=Added
44 20. DataRow nrow=aDataSet.Tables["Table1"].NewRow();
45 21. for(int j=0;j<newds.Tables[0].Columns.Count;j++)
46 22. {
47 23. nrow[j]=oldds.Tables[0].Rows[i][j];
48 24. }
49 25. newds.Tables["Table1"].Rows.Add(nrow);
50 26. }
51 27. myCommand.Update(newds,"Table1");
52 28. myConn.Close();
53 29.}
54
55 ASP.NET读取Excel文件方法二:引用的com组件:Microsoft.Office.Interop.Excel.dll读取Excel文件
56
57 首先是Excel.dll的获取,将Office安装目录下的Excel.exe文件Copy到DotNet的bin目录下,cmd到该目录下,运行 TlbImp EXCEL.EXE Excel.dll 得到Dll文件。
58
59 在项目中添加引用该dll文件.
60 01.//读取EXCEL的方法 (用范围区域读取数据)
61 02.private void OpenExcel(string strFileName)
62 03.{
63 04. object missing = System.Reflection.Missing.Value;
64 05. Application excel = new Application();//lauch excel application
65 06. if (excel == null)
66 07. {
67 08. Response.Write("<script>alert('Can't access excel')</script>");
68 09. }
69 10. else
70 11. {
71 12. excel.Visible = false; excel.UserControl = true;
72 13. // 以只读的形式打开EXCEL文件
73 14. Workbook wb = excel.Application.Workbooks.Open(strFileName, missing, true, missing, missing, missing,
74 15. missing, missing, missing, true, missing, missing, missing, missing, missing);
75 16. //取得第一个工作薄
76 17. Worksheet ws = (Worksheet)wb.Worksheets.get_Item(1);
77 18. //取得总记录行数 (包括标题列)
78 19. int rowsint = ws.UsedRange.Cells.Rows.Count; //得到行数
79 20. //int columnsint = mySheet.UsedRange.Cells.Columns.Count;//得到列数
80 21. //取得数据范围区域 (不包括标题列)
81 22. Range rng1 = ws.Cells.get_Range("B2", "B" + rowsint); //item
82 23. Range rng2 = ws.Cells.get_Range("K2", "K" + rowsint); //Customer
83 24. object[,] arryItem= (object[,])rng1.Value2; //get range's value
84 25. object[,] arryCus = (object[,])rng2.Value2;
85 26. //将新值赋给一个数组
86 27. string[,] arry = new string[rowsint-1, 2];
87 28. for (int i = 1; i <= rowsint-1; i++)
88 29. {
89 30. //Item_Code列
90 31. arry[i - 1, 0] =arryItem[i, 1].ToString();
91 32. //Customer_Name列
92 33. arry[i - 1, 1] = arryCus[i, 1].ToString();
93 34. }
94 35. Response.Write(arry[0, 0] + " / " + arry[0, 1] + "#" + arry[rowsint - 2, 0] + " / " + arry[rowsint - 2, 1]);
95 36. }
96 37. excel.Quit(); excel = null;
97 38. Process[] procs = Process.GetProcessesByName("excel");
98 39. foreach (Process pro in procs)
99 40. {
100 41. pro.Kill();//没有更好的方法,只有杀掉进程
101 42. }
102 43. GC.Collect();
103 44.}
104
105 ASP.NET读取Excel文件方法三:将Excel文件转化成CSV(逗号分隔)的文件,用文件流读取(等价就是读取一个txt文本文件)。
106
107 先引用命名空间:
108 01.using System.Text;和using System.IO;
109 02.FileStream fs = new FileStream("d:\\Customer.csv", FileMode.Open, FileAccess.Read, FileShare.None);
110 03.StreamReader sr = new StreamReader(fs, System.Text.Encoding.GetEncoding(936));
111 04.string str = "";
112 05.string s = Console.ReadLine();
113 06.while (str != null)
114 07.{
115 08. str = sr.ReadLine();
116 09. string[] xu = new String[2];
117 10. xu = str.Split(',');
118 11. string ser = xu[0];
119 12. string dse = xu[1];
120 13. if (ser == s)
121 14. {
122 15. Console.WriteLine(dse);break;
123 16. }
124 17.}
125 18.sr.Close();
126
127 另外也可以将数据库数据导入到一个txt文件,实例如下:
128
129 01.//txt文件名
130 02.string fn = DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + "PO014" + ".txt";
131 03.OleDbConnection con = new OleDbConnection(conStr);
132 04.con.Open();
133 05.string sql = "select ITEM,REQD_DATE,QTY,PUR_FLG,PO_NUM from TSD_PO014";
134 06./OleDbCommand mycom = new OleDbCommand("select * from TSD_PO014", mycon);
135 07.//OleDbDataReader myreader = mycom.ExecuteReader(); //也可以用Reader读取数据
136 08.DataSet ds = new DataSet();
137 09.OleDbDataAdapter oda = new OleDbDataAdapter(sql, con);
138 10.oda.Fill(ds, "PO014");
139 11.DataTable dt = ds.Tables[0];
140 12.FileStream fs = new FileStream(Server.MapPath("download/" + fn), FileMode.Create, FileAccess.ReadWrite);
141 13.StreamWriter strmWriter = new StreamWriter(fs); //存入到文本文件中
142 14.//把标题写入.txt文件中
143 15.//for (int i = 0; i <dt.Columns.Count;i++)
144 16.//{
145 17.// strmWriter.Write(dt.Columns[i].ColumnName + " ");
146 18.//}
147 19.foreach (DataRow dr in dt.Rows)
148 20.{
149 21. string str0, str1, str2, str3;
150 22. string str = "|"; //数据用"|"分隔开
151 23. str0 = dr[0].ToString();
152 24. str1 = dr[1].ToString();
153 25. str2 = dr[2].ToString();
154 26. str3 = dr[3].ToString();
155 27. str4 = dr[4].ToString().Trim();
156 28. strmWriter.Write(str0);
157 29. strmWriter.Write(str);
158 30. strmWriter.Write(str1);
159 31. strmWriter.Write(str);
160 32. strmWriter.Write(str2);
161 33. strmWriter.Write(str);
162 34. strmWriter.Write(str3);
163 35. strmWriter.WriteLine(); //换行
164 36.}
165 37.strmWriter.Flush();
166 38.strmWriter.Close();
167 39.if (con.State == ConnectionState.Open)
168 40.{
169 41. con.Close();
170 42.}
171