c读取excel文件的几种方法.docx

上传人:b****4 文档编号:27192346 上传时间:2023-06-28 格式:DOCX 页数:11 大小:18.04KB
下载 相关 举报
c读取excel文件的几种方法.docx_第1页
第1页 / 共11页
c读取excel文件的几种方法.docx_第2页
第2页 / 共11页
c读取excel文件的几种方法.docx_第3页
第3页 / 共11页
c读取excel文件的几种方法.docx_第4页
第4页 / 共11页
c读取excel文件的几种方法.docx_第5页
第5页 / 共11页
点击查看更多>>
下载资源
资源描述

c读取excel文件的几种方法.docx

《c读取excel文件的几种方法.docx》由会员分享,可在线阅读,更多相关《c读取excel文件的几种方法.docx(11页珍藏版)》请在冰豆网上搜索。

c读取excel文件的几种方法.docx

c读取excel文件的几种方法

C#读取EXCEL文件的几种经典方法

 

例子引入(读取时excel要打开)

namespace读取excel测试

{

publicpartialclassForm1:

Form

{

publicForm1()

{

InitializeComponent();

}

//读取

privatevoidsimpleButton1_Click(objectsender,EventArgse)

{

bindingSource1.DataSource=null;

OpenFileDialogfd=newOpenFileDialog();

fd.Filter="电子表À格|*.xlsx|电子表格|*.xls|所有文件|*.*";

//打开对话框

if(fd.ShowDialog()==DialogResult.OK)

{

//得到文件路径名称

this.txtPath.Text=fd.FileName;

//将excel的对象放到bindingSource1中预览

DataTabledt=returndb(this.txtPath.Text).Tables[0];

bindingSource1.DataSource=dt;

gridView1.BestFitColumns();

}

}

//读取方法

publicDataSetreturndb(stringpath)

{

stringstrConn="Provider=Microsoft.Jet.OLEDB.4.0;"+"DataSource="+path+";"+"ExtendedProperties=Excel8.0;";

OleDbConnectionconn=newOleDbConnection(strConn);

conn.Open();

stringstrExcel="";

OleDbDataAdaptermyCommand=null;

DataSetds=null;

strExcel="select*from[sheet1$]";

myCommand=newOleDbDataAdapter(strExcel,strConn);

ds=newDataSet();

myCommand.Fill(ds,"table1");

returnds;

//另一种写法

//FileInfofileInfo=newFileInfo(path);

//if(!

fileInfo.Exists)returnnull;

//stringstrConn=@"Provider=Microsoft.Jet.OLEDB.4.0;DataSource="+path+";ExtendedProperties='Excel8.0;HDR=NO;IMEX=1'";

//OleDbConnectionobjConn=newOleDbConnection(strConn);

//DataSetdsExcel=newDataSet();

//try

//{

//objConn.Open();

//DataTabletable=objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables,null);

//stringtableName=table.Rows[0]["Table_Name"].ToString();

//stringstrSql="select*from["+tableName+"]";

//OleDbDataAdapterodbcExcelDataAdapter=newOleDbDataAdapter(strSql,objConn);

//odbcExcelDataAdapter.Fill(dsExcel);

//returndsExcel;

//}

//catch(Exceptionex)

//{

//throwex;

//}

}

}

}

1.方法一:

采用OleDB读取EXCEL文件:

把EXCEL文件当做一个数据源来进行数据的读取操作,实例如下:

publicDataSetExcelToDS(stringPath)

{

stringstrConn="Provider=Microsoft.Jet.OLEDB.4.0;"+"DataSource="+Path+";"+"ExtendedProperties=Excel8.0;";

OleDbConnectionconn=newOleDbConnection(strConn);

conn.Open();

stringstrExcel="";

OleDbDataAdaptermyCommand=null;

DataSetds=null;

strExcel="select*from[sheet1$]";

myCommand=newOleDbDataAdapter(strExcel,strConn);

ds=newDataSet();

myCommand.Fill(ds,"table1");

returnds;

}

对于EXCEL中的表即sheet([sheet1$])如果不是固定的可以使用下面的方法得到

stringstrConn="Provider=Microsoft.Jet.OLEDB.4.0;"+"DataSource="+Path+";"+"ExtendedProperties=Excel8.0;";

OleDbConnectionconn=newOleDbConnection(strConn);

DataTableschemaTable=objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables,null);

stringtableName=schemaTable.Rows[0][2].ToString().Trim();

另外:

也可进行写入EXCEL文件,实例如下:

publicvoidDSToExcel(stringPath,DataSetoldds)

{

//先得到汇总EXCEL的DataSet主要目的是获得EXCEL在DataSet中的结构

stringstrCon="Provider=Microsoft.Jet.OLEDB.4.0;DataSource="+path1+";ExtendedProperties=Excel8.0";

OleDbConnectionmyConn=newOleDbConnection(strCon);

stringstrCom="select*from[Sheet1$]";

myConn.Open();

OleDbDataAdaptermyCommand=newOleDbDataAdapter(strCom,myConn);

ystem.Data.OleDb.OleDbCommandBuilderbuilder=newOleDbCommandBuilder(myCommand);

//QuotePrefix和QuoteSuffix主要是对builder生成InsertComment命令时使用。

builder.QuotePrefix="[";//获取insert语句中保留字符(起始位置)

builder.QuoteSuffix="]";//获取insert语句中保留字符(结束位置)

DataSetnewds=newDataSet();

myCommand.Fill(newds,"Table1");

for(inti=0;i

{

//在这里不能使用ImportRow方法将一行导入到news中,因为ImportRow将保留原来DataRow的所有设置(DataRowState状态不变)。

在使用ImportRow后newds内有值,但不能更新到Excel中因为所有导入行的DataRowState!

=Added

DataRownrow=aDataSet.Tables["Table1"].NewRow();

for(intj=0;j

{

nrow[j]=oldds.Tables[0].Rows[i][j];

}

newds.Tables["Table1"].Rows.Add(nrow);

}

myCommand.Update(newds,"Table1");

myConn.Close();

}

 

2.方法二:

引用的com组件:

Microsoft.Office.Interop.Excel.dll读取EXCEL文件首先是Excel.dll的获取,将Office安装目录下的Excel.exe文件Copy到DotNet的bin目录下,cmd到该目录下,运行TlbImpEXCEL.EXEExcel.dll得到Dll文件。

再在项目中添加引用该dll文件.

//读取EXCEL的方法(用范围区域读取数据)

privatevoidOpenExcel(stringstrFileName)

{

objectmissing=System.Reflection.Missing.Value;

Applicationexcel=newApplication();//lauchexcelapplication

if(excel==null)

{

Response.Write("");

}

else

{

excel.Visible=false;excel.UserControl=true;

//以只读的形式打开EXCEL文件

Workbookwb=excel.Application.Workbooks.Open(strFileName,missing,true,missing,missing,missing,

missing,missing,missing,true,missing,missing,missing,missing,missing);

//取得第一个工作薄

Worksheetws=(Worksheet)wb.Worksheets.get_Item

(1);

//取得总记录行数(包括标题列)

introwsint=ws.UsedRange.Cells.Rows.Count;//得到行数

//intcolumnsint=mySheet.UsedRange.Cells.Columns.Count;//得到列数

//取得数据范围区域(不包括标题列)

Rangerng1=ws.Cells.get_Range("B2","B"+rowsint);//item

Rangerng2=ws.Cells.get_Range("K2","K"+rowsint);//Customer

object[,]arryItem=(object[,])rng1.Value2;//getrange'svalue

object[,]arryCus=(object[,])rng2.Value2;

//将新值赋给一个数组

string[,]arry=newstring[rowsint-1,2];

for(inti=1;i<=rowsint-1;i++)

{

//Item_Code列

arry[i-1,0]=arryItem[i,1].ToString();

//Customer_Name列

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(Processproinprocs)

{

pro.Kill();//没有更好的方法,只有杀掉进程

}

GC.Collect();

}

 

3.方法三:

将EXCEL文件转化成CSV(逗号分隔)的文件,用文件流读取(等价就是读取一个txt文本文件)。

先引用命名空间:

usingSystem.Text;和usingSystem.IO;

FileStreamfs=newFileStream("d:

\\Customer.csv",FileMode.Open,FileAccess.Read,FileShare.None);

StreamReadersr=newStreamReader(fs,System.Text.Encoding.GetEncoding(936));

stringstr="";

strings=Console.ReadLine();

while(str!

=null)

{str=sr.ReadLine();

string[]xu=newString[2];

xu=str.Split(',');

stringser=xu[0];

stringdse=xu[1];

if(ser==s)

{

Console.WriteLine(dse);

break;

}

}

sr.Close();

 

另外也可以将数据库数据导入到一个txt文件,实例如下:

//txt文件名

stringfn=DateTime.Now.ToString("yyyyMMddHHmmss")+"-"+"PO014"+".txt";

OleDbConnectioncon=newOleDbConnection(conStr);

con.Open();

stringsql="selectITEM,REQD_DATE,QTY,PUR_FLG,PO_NUMfromTSD_PO014";

//OleDbCommandmycom=newOleDbCommand("select*fromTSD_PO014",mycon);

//OleDbDataReadermyreader=mycom.ExecuteReader();//也可以用Reader读取数据

DataSetds=newDataSet();

OleDbDataAdapteroda=newOleDbDataAdapter(sql,con);

oda.Fill(ds,"PO014");

DataTabledt=ds.Tables[0];

FileStreamfs=newFileStream(Server.MapPath("download/"+fn),FileMode.Create,FileAccess.ReadWrite);

StreamWriterstrmWriter=newStreamWriter(fs);//存入到文本文件中

//把标题写入.txt文件中

//for(inti=0;i

//{

//strmWriter.Write(dt.Columns[i].ColumnName+"");

//}

foreach(DataRowdrindt.Rows)

{

stringstr0,str1,str2,str3;

stringstr="|";//数据用"|"分隔开

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();

}

 

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 总结汇报 > 学习总结

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1