【转】 C# 操作excel 大全

A>Read 
 有两种方法:
  a.OleDbConnection 示例代码如下:
 1  String connStr = " Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + strFilePath + " ;Extended Properties=Excel 8.0; " ;
 2  System.Data.OleDb.OleDbConnection con = new  System.Data.OleDb.OleDbConnection(connStr);
 3  System.Data.OleDb.OleDbDataAdapter oda = new  System.Data.OleDb.OleDbDataAdapter( " select * from [Sheet1$] " ,con);
 4  System.Data.DataSet ds = new  System.Data.DataSet();
 5  oda.Fill(ds);
 6  String[] SrcterminalId = new  String[ds.Tables[ 0 ].Rows.Count];
 7  String[] DestterminalId = new  String[ds.Tables[ 0 ].Rows.Count];
 8  String[] SendContent = new  String[ds.Tables[ 0 ].Rows.Count];
 9  for (Int32 i = 0 ;i < ds.Tables[ 0 ].Rows.Count;i ++ )
10  { // 从第0行,第0列开始
11       if (ds.Tables[ 0 ].Rows[i][ 0 ].ToString() != "" )
12      {                    SrcterminalId[i] = ds.Tables[ 0 ].Rows[i][ 0 ].ToString();
13      }
14       if (ds.Tables[ 0 ].Rows[i][ 1 ].ToString() != "" )
15      {                    DestterminalId[i] = ds.Tables[ 0 ].Rows[i][ 1 ].ToString();        
16      }
17       if (ds.Tables[ 0 ].Rows[i][ 2 ].ToString() != "" )
18      {                    SendContent[i] = ds.Tables[ 0 ].Rows[i][ 2 ].ToString();
19      }                
20  }
21 
大家会发现数据会丢失的现象, 将EXCEL数据导出的时候如果同一列数据中既有文字,又有数字!读取时一列中要么文字丢失只剩下数字,要么数字丢失,只剩下文字,这是由第一行的数据类型决定的。出现这种问题是由于数据类型不统一造成的。原来的连接字符串为 String connStr="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+strFilePath+";Extended Properties=Excel 8.0;";查阅资料后问题解决: String connStr="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+strFilePath+";Extended Properties='Excel 8.0;IMEX=1'";
其中参数解释:
HDR=YES    有两个值:YES/NO,表示第一行是否字段名,默认是YES,第一行是字段名
IMEX=1   解决数字与字符混合时,识别不正常的情况
  b.调用Com组件 需要添加Microsot.Excel 9.0 Object Library组件。
 1  // 创建Application对象
 2  Excel.Application app = new  Excel.ApplicationClass();
 3  // 是否显示Excel,默认为false
 4  app.Visible = false ;
 5  Object o = System.Reflection.Missing.Value;
 6  Excel.WorkbookClass w = (Excel.WorkbookClass)app.Workbooks.Open(strFilePath,o,o,o,o,o,o,o,o,o,o,o,o);
 7  Excel.Sheets sheets = w.Worksheets;
 8  Excel.Worksheet datasheet = null ;
 9  foreach (Excel.Worksheet sheet  in  sheets)
10  {
11       if (sheet.Name == " Sheet1 " )
12      {                            datasheet = sheet;
13           break ;
14      }
15  }
16  if (datasheet != null )
17  // ds还是采用上面的取行写法,如果不这样,不知道读几行
18       for (Int32 i = 0 ;i < ds.Tables[ 0 ].Rows.Count;i ++ )
19      {  // 从第二行,第一列开始
20          
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liycumt

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值