最近研究了如何使得ASP.NET读取Excel文件更加高效呢,现总结如下:
ASP.NET读取Excel文件方法一:采用OleDB读取Excel文件:
把Excel文件当做一个数据源来进行数据的读取操作,实例如下:
-
public DataSet ExcelToDS(string Path)
- {
-
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;";
-
OleDbConnection conn = new OleDbConnection(strConn);
- conn.Open();
-
string strExcel = "";
- OleDbDataAdapter myCommand = null;
- DataSet ds = null;
-
strExcel="select * from [sheet1$]";
-
myCommand = new OleDbDataAdapter(strExcel, strConn);
-
ds = new DataSet();
-
myCommand.Fill(ds,"table1");
-
return ds;
- }
对于Excel中的表即sheet([sheet1$])如果不是固定的可以使用下面的方法得到
-
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;";
-
OleDbConnection conn = new OleDbConnection(strConn);
- DataTable schemaTable = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables,null);
- string tableName=schemaTable.Rows[0][2].ToString().Trim();
另外:也可进行写入Excel文件,实例如下:
-
public void DSToExcel(string Path,DataSet oldds)
- {
-
-
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source ="+path1+";Extended Properties=Excel 8.0" ;
-
OleDbConnection myConn = new OleDbConnection(strCon) ;
-
string strCom="select * from [Sheet1$]";
- myConn.Open ( ) ;
-
OleDbDataAdapter myCommand = new OleDbDataAdapter ( strCom, myConn ) ;
-
ystem.Data.OleDb.OleDbCommandBuilder builder=new OleDbCommandBuilder(myCommand);
-
-
builder.QuotePrefix="[";
-
builder.QuoteSuffix="]";
-
DataSet newds=new DataSet();
-
myCommand.Fill(newds ,"Table1") ;
-
for(int i=0;i<oldds.Tables[0].Rows.Count;i++)
- {
-
-
-
DataRow nrow=aDataSet.Tables["Table1"].NewRow();
-
for(int j=0;j<newds.Tables[0].Columns.Count;j++)
- {
- nrow[j]=oldds.Tables[0].Rows[i][j];
- }
-
newds.Tables["Table1"].Rows.Add(nrow);
- }
-
myCommand.Update(newds,"Table1");
- myConn.Close();
- }
ASP.NET读取Excel文件方法二:引用的com组件:Microsoft.Office.Interop.Excel.dll读取Excel文件
首先是Excel.dll的获取,将Office安装目录下的Excel.exe文件Copy到DotNet的bin目录下,cmd到该目录下,运行 TlbImp EXCEL.EXE Excel.dll 得到Dll文件。
在项目中添加引用该dll文件.
-
-
private void OpenExcel(string strFileName)
- {
- object missing = System.Reflection.Missing.Value;
-
Application excel = new Application();
-
if (excel == null)
- {
-
Response.Write("<script>alert('Can't access excel')</script>");
- }
-
else
- {
-
excel.Visible = false; excel.UserControl = true;
-
-
Workbook wb = excel.Application.Workbooks.Open(strFileName, missing, true, missing, missing, missing,
-
missing, missing, missing, true, missing, missing, missing, missing, missing);
-
- Worksheet ws = (Worksheet)wb.Worksheets.get_Item(1);
-
-
-
int rowsint = ws.UsedRange.Cells.Rows.Count;
-
-
-
-
Range rng1 = ws.Cells.get_Range("B2", "B" + rowsint);
-
-
Range rng2 = ws.Cells.get_Range("K2", "K" + rowsint);
-
object[,] arryItem= (object[,])rng1.Value2;
- object[,] arryCus = (object[,])rng2.Value2;
-
-
string[,] arry = new string[rowsint-1, 2];
-
for (int i = 1; i <= rowsint-1; i++)
- {
-
- arry[i - 1, 0] =arryItem[i, 1].ToString();
-
- arry[i - 1, 1] = arryCus[i, 1].ToString();
- }
-
Response.Write(arry[0, 0] + " / " + arry[0, 1] + "#" + arry[rowsint - 2, 0] + " / " + arry[rowsint - 2, 1]);
- }
- excel.Quit(); excel = null;
-
Process[] procs = Process.GetProcessesByName("excel");
-
- foreach (Process pro in procs)
- {
-
pro.Kill();
- }
- GC.Collect();
- }
ASP.NET读取Excel文件方法三:将Excel文件转化成CSV(逗号分隔)的文件,用文件流读取(等价就是读取一个txt文本文件)。
先引用命名空间:
-
using System.Text;和using System.IO;
-
FileStream fs = new FileStream("d:\\Customer.csv", FileMode.Open, FileAccess.Read, FileShare.None);
-
StreamReader sr = new StreamReader(fs, System.Text.Encoding.GetEncoding(936));
-
-
string str = "";
-
string s = Console.ReadLine();
-
while (str != null)
- { str = sr.ReadLine();
-
string[] xu = new String[2];
-
xu = str.Split(',');
-
string ser = xu[0];
-
string dse = xu[1]; if (ser == s)
-
{ Console.WriteLine(dse);break;
- }
- } sr.Close();
另外也可以将数据库数据导入到一个txt文件,实例如下:
-
-
string fn = DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + "PO014" + ".txt";
-
-
OleDbConnection con = new OleDbConnection(conStr);
- con.Open();
-
string sql = "select ITEM,REQD_DATE,QTY,PUR_FLG,PO_NUM from TSD_PO014";
-
/OleDbCommand mycom = new OleDbCommand("select * from TSD_PO014", mycon);
-
-
DataSet ds = new DataSet();
-
OleDbDataAdapter oda = new OleDbDataAdapter(sql, con);
-
oda.Fill(ds, "PO014");
- DataTable dt = ds.Tables[0];
-
-
FileStream fs = new FileStream(Server.MapPath("download/" + fn), FileMode.Create, FileAccess.ReadWrite);
-
StreamWriter strmWriter = new StreamWriter(fs);
-
-
-
-
-
-
-
-
foreach (DataRow dr in dt.Rows)
- {
-
string str0, str1, str2, str3;
-
string str = "|";
- str0 = dr[0].ToString();
- str1 = dr[1].ToString();
- str2 = dr[2].ToString();
- str3 = dr[3].ToString();
- str4 = dr[4].ToString().Trim();
- strmWriter.Write(str0);
- strmWriter.Write(str);
- strmWriter.Write(str1);
- strmWriter.Write(str);
- strmWriter.Write(str2);
- strmWriter.Write(str);
- strmWriter.Write(str3);
-
strmWriter.WriteLine();
- }
- strmWriter.Flush();
- strmWriter.Close();
-
if (con.State == ConnectionState.Open)
- {
- con.Close();
- }
ASP.NET读取Excel文件的方法就向你介绍到这里,希望对你了解ASP.NET读取Excel文件有所帮助。
【编辑推荐】
- ASP.NET程序员的学习之路杂谈
- ASP.NET自定义控件开发浅析
- ASP.NET服务器控件之生命周期浅析
- ASP.NET中Excel动态实现浅析
-
ASP.NET操作Excel注意事项浅析
【责任编辑:
李彦光 TEL:(010)68476606】
请发表评论