C#读取excel等表格常用方法
0. 利用NPOI。 请查阅此插件的相关文档。
1.方法一:采用OleDB读取EXCEL文件: 把EXCEL文件当做一个数据源来进行数据的读取操作,实例如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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$])如果不是固定的可以使用下面的方法得到
1
2
3
4
|
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文件,实例如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
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文件.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
//读取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文本文件)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
先引用命名空间: 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文件,实例如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
//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等表格常用方法的更多相关文章
- 【c#操作office】--OleDbDataAdapter 与OleDbDataReader方式读取excel,并转换为datatable
OleDbDataAdapter方式: /// <summary> /// 读取excel的表格放到DataTable中 ---OleDbDataAdapter /// </summ ...
- Java读取excel表格
Java读取excel表格 一般都是用poi技术去读取excel表格的,但是这个技术又是什么呢 什么是Apache POI? Apache POI是一种流行的API,它允许程序员使用Java程序创建, ...
- Java POI读取Excel数据,将数据写入到Excel表格
1.准备 首先需要导入poi相应的jar包,包括: 下载地址:http://pan.baidu.com/s/1bpoxdz5 所需要的包的所在位置包括: 2.读取Excel数据代码 package S ...
- C#读取Excel表格中数据并返回datatable
在软件开发的过程中,经常用到从excel表格中读取数据作为数据源,以下整理了一个有效的读取excel表格的方法. DataTable GetDataTable(string tableName,str ...
- 利用java反射机制实现读取excel表格中的数据
如果直接把excel表格中的数据导入数据库,首先应该将excel中的数据读取出来. 为了实现代码重用,所以使用了Object,而最终的结果是要获取一个list如List<User>.Lis ...
- 读取Excel表格中数据原型
写下这篇博客来记录自己的工作,这部分功能是读取Excel表格中的数据,并通过c#中的datagridview控件将读取的数据显示出来.为了方便用户,我设计了一个read按钮,用户点击这个按钮,会弹出打 ...
- java用poi读取Excel表格中的数据
Java读写Excel的包是Apache POI(项目地址:http://poi.apache.org/),因此需要先获取POI的jar包,本实验使用的是POI 3.9稳定版.Apache POI 代 ...
- C#读取Excel表格的数据
1.创建工程后,需要下载 EPPlus.dll 添加到工程中,这里有一个下载地址:https://download.csdn.net/download/myunity/10784634 2.下面仅实现 ...
- 读取excel表格以及生成自动化报告
数据库读取 标签(空格分隔): 数据库读取 读excel数据xlrd 当登录的账号有多个的时候,我们一般用excel存放测试数据,本节课介绍,python读取excel方法,并保存为字典格式. 1.先 ...
随机推荐
- android一个上传图片的样例,包含怎样终止上传过程,假设在上传的时候更新进度条(一)
先上效果图: Layout为: <? xml version="1.0" encoding="utf-8"?> <LinearLayout x ...
- ORACLE数据库常见问题汇总
提交事务的时候提示(数据库被一个用户锁住的解决方法) select object_id,session_id,locked_mode from v$locked_object; select t2.u ...
- 1T文件夹 - 微云
1T文件夹 - 微云 1T文件夹
- Python基础 - 内建函数
什么是内建函数 在Python的手册中,名叫build-in Functions,中文可以称为内建函数. 内建函数就像dos系统的内部命令,他不依赖于外部模块,也就是说: 内建函数就是:安装好Pyth ...
- 利用json获取天气信息
天气预报信息获取是利用json获取的,网上有非常多资源,源码.因为上面涉及到非常多天气信息,包含湿度,出行建议等,以及加入了全部城市代码的资源包.为了练手了解json的原理.我仅获取诚笃城市的最高温, ...
- nginx fastcgi 自定义错误页面
http{ fastcgi_intercept_errors on; error_page 404 /404.html; } fastcgi_intercept_errors on;必须设置 之后通过 ...
- Amazon.com : The Odyssey of the Manual Toothbrusher
Amazon.com : The Odyssey of the Manual Toothbrusher The Odyssey of the Manual Toothbrusher
- poj2253(最短路小变形)
题目连接:http://poj.org/problem?id=2253 题意:给出一个无向图,求一条1~2的路径使得路径上的最大边权最小. 分析:dij将距离更新改成取最大值即可,即dp[i]表示到达 ...
- 单片机实验: 三轴磁场模块 GY-271
最近买了一块三轴磁场模块进行实验 名称:HMC5883L模块(三轴磁场模块) 型号:GY-271 使用芯片:HMC5883L 供电电源:3-5v 通信方式:IIC通信协议 测量范围:±1.3-8 高斯 ...
- Python的Tkinter将窗口置顶
root = Tk()root.wm_attributes('-topmost',1)