1.方法一:采用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)
{
//先得到汇总EXCEL的DataSet 主要目的是获得EXCEL在DataSet中的结构
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);
//QuotePrefix和QuoteSuffix主要是对builder生成InsertComment命令时使用。
builder.QuotePrefix="["; //获取insert语句中保留字符(起始位置)
builder.QuoteSuffix="]"; //获取insert语句中保留字符(结束位置)
DataSet newds=new DataSet();
myCommand.Fill(newds ,"Table1") ;
for(int i=0;i<oldds.Tables[0].Rows.Count;i++)
{
//在这里不能使用ImportRow方法将一行导入到news中,因为ImportRow将保留原来DataRow的所有设置(DataRowState状态不变)。
在使用ImportRow后newds内有值,但不能更新到Excel中因为所有导入行的DataRowState!=Added
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();
}

2.方法二:引用的com组件:Microsoft.Office.Interop.Excel.dll   读取EXCEL文件 
首先是Excel.dll的获取,将Office安装目录下的Excel.exe文件Copy到DotNet的bin目录下,cmd到该目录下,运行 TlbImp EXCEL.EXE Excel.dll 得到Dll文件。 再在项目中添加引用该dll文件.

    //读取EXCEL的方法   (用范围区域读取数据)
private void OpenExcel(string strFileName)
{
object missing = System.Reflection.Missing.Value;
Application excel = new Application();//lauch excel application
if (excel == null)
{
Response.Write("<script>alert('Can't access excel')</script>");
}
else
{
excel.Visible = false; excel.UserControl = true;
// 以只读的形式打开EXCEL文件
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; //得到行数
//int columnsint = mySheet.UsedRange.Cells.Columns.Count;//得到列数 //取得数据范围区域 (不包括标题列)
Range rng1 = ws.Cells.get_Range("B2", "B" + rowsint); //item Range rng2 = ws.Cells.get_Range("K2", "K" + rowsint); //Customer
object[,] arryItem= (object[,])rng1.Value2; //get range's value
object[,] arryCus = (object[,])rng2.Value2;
//将新值赋给一个数组
string[,] arry = new string[rowsint-1, 2];
for (int i = 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 (Process pro in procs)
{
pro.Kill();//没有更好的方法,只有杀掉进程
}
GC.Collect();
}

3.方法三:将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文件,实例如下:

        //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);
//OleDbDataReader myreader = mycom.ExecuteReader(); //也可以用Reader读取数据
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); //存入到文本文件中 //把标题写入.txt文件中
//for (int i = 0; i <dt.Columns.Count;i++)
//{
// strmWriter.Write(dt.Columns[i].ColumnName + " ");
//} 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();
}

C#中excel读取和写入的更多相关文章

  1. Pandas之Dateframe 实现Excel读取与写入

    目的:有时需对数据进行到出到Excel,直观的给别人参阅,或从Excel中读取数据进行操作和分析依赖库 pandas 可简单的读出和写入 1,根据Excel读取( 需安装xlrd库) import n ...

  2. C#连接Excel读取与写入数据库SQL ( 上 )

    第一次写C#与sql的东西,主要任务是从Excel读取数据,再存到SQL server中. 先上读取Excel文件的code如下. public bool GetFiles(string equipN ...

  3. 在线程中进行读取并写入文件和wenjia

    新人求(胸)罩!!! import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException ...

  4. Excelvba从文件中逐行读取并写入excel中

    Sub 読み込む() Dim result As Long Dim dialog As FileDialog Set dialog = Application.FileDialog(msoFileDi ...

  5. python使用 openpyxl包 excel读取与写入

    '''### 写入操作 ###from openpyxl import Workbook#实例化对象wb=Workbook()#创建表ws1=wb.create_sheet('work',0) #默认 ...

  6. 使用java进行excel读取和写入

    1:添加处理excel的依赖jar包 <!-- 引入poi,解析workbook视图 --> <dependency> <groupId>org.apache.po ...

  7. Python调用百度地图API实现批量经纬度转换为实际省市地点(api调用,json解析,excel读取与写入)

    1.获取秘钥 调用百度地图API实现得申请百度账号或者登陆百度账号,然后申请自己的ak秘钥.链接如下:http://lbsyun.baidu.com/apiconsole/key?applicatio ...

  8. C#连接Excel读取与写入数据库SQL ( 下 )

    接上期 dataset简而言之可以理解为 虚拟的 数据库或是Excel文件.而dataset里的datatable 可以理解为数据库中的table活着Excel里的sheet(Excel里面不是可以新 ...

  9. 【Python】sasa版:文件中csv读取在写入csv读取的数据和执行是否成功。

    sasa写的文件(包含解析文字) # coding=utf- from selenium import webdriver from time import sleep import keyword ...

随机推荐

  1. JQuery+ajax数据加载..........

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  2. POJ 2187 Beauty Contest(凸包+旋转卡壳)

    Description Bessie, Farmer John's prize cow, has just won first place in a bovine beauty contest, ea ...

  3. 课堂练习之找数字0-N中“1”出现的次数

    一.题目与要求 题目:给定一个十进制的正整数,写下从1开始,到N的所有整数,然后数一下其中出现“1”的个数. 要求:1.写一个函数 f(N) ,返回1 到 N 之间出现的“1”的个数.例如 f(12) ...

  4. C++视频教学

    http://open.163.com/movie/2010/1/E/4/M6LDTAPTU_M6LFSTGE4.html http://open.163.com/movie/2010/1/N/5/M ...

  5. XML 反序列化成对象,绑定到CheckBoxList控件

    1.前台 <div class="control-group"> <label class="control-label"> 导航名称: ...

  6. Expected Conditions的常用函数

    Expected Conditions的使用场景有两种  1.直接在断言中使用  2.与WebDriverWait配合使用,动态等待页面上元素出现或者消失 1. title_is: 判断当前页面的ti ...

  7. BZOJ 1004 Cards(Burnside引理+DP)

    因为有着色数的限制,故使用Burnside引理. 添加一个元置换(1,2,,,n)形成m+1种置换,对于每个置换求出循环节的个数, 每个循环节的长度. 则ans=sigma(f(i))/(m+1) % ...

  8. BZOJ 1040 骑士(环套树DP)

    如果m=n-1,显然这就是一个经典的树形dp. 现在是m=n,这是一个环套树森林,破掉这个环后,就成了一个树,那么这条破开的边连接的两个顶点不能同时选择.我们可以对这两个点进行两次树形DP根不选的情况 ...

  9. bzoj3473字符串&bzoj3277串

    题意:给定n个字符串,询问每个字符串有多少子串(不包括空串)是所有n个字符串中至少k个字符串的子串.注意本质相同的子串多次出现算多次,如1 1 aaa这组数据答案为6,贡献1WA.代码里有些部分是为了 ...

  10. 【codevs1380】没有上司的舞会 树形dp

    题目描述 Ural大学有N个职员,编号为1~N.他们有从属关系,也就是说他们的关系就像一棵以校长为根的树,父结点就是子结点的直接上司.每个职员有一个快乐指数.现在有个周年庆宴会,要求与会职员的快乐指数 ...