求C# 操作Excel操作资料

li_rui_1220 2014-08-01 02:24:04
如题:急需C#操作Excel方面的资料,我使用的是VS2012.
非常感谢!!
...全文
418 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
曹虫 2014-08-04
  • 打赏
  • 举报
回复
曹虫 2014-08-04
  • 打赏
  • 举报
回复
using System; using System.Data; using System.Data.SqlClient; using System.Data.OleDb; using System.IO; public class Excel_Data { public Excel_Data() { // // TODO: 在此处添加构造函数逻辑 // } #region 处理Excel文件 /// <summary> /// 将指定Excel文件中的数据转换成DataTable对象,供应用程序进一步处理 /// </summary> /// <param name="filePath"></param> /// <returns></returns> public DataTable Import(string filePath) { System.Data.DataTable rs = new System.Data.DataTable(); bool canOpen=false; OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;"+ "Data Source=" + filePath + ";" + "Extended Properties=\"Excel 8.0;\""); try//尝试数据连接是否可用 { conn.Open(); conn.Close(); canOpen=true; } catch{} if(canOpen) { try//如果数据连接可以打开则尝试读入数据 { OleDbCommand myOleDbCommand = new OleDbCommand("SELECT * FROM [Sheet1$]",conn); OleDbDataAdapter myData = new OleDbDataAdapter(myOleDbCommand); myData.Fill(rs); conn.Close(); } catch//如果数据连接可以打开但是读入数据失败,则从文件中提取出工作表的名称,再读入数据 { string sheetName=GetSheetName(filePath); if(sheetName.Length>0) { OleDbCommand myOleDbCommand = new OleDbCommand("SELECT * FROM ["+sheetName+"$]",conn); OleDbDataAdapter myData = new OleDbDataAdapter(myOleDbCommand); myData.Fill(rs); conn.Close(); } } } else { System.IO.StreamReader tmpStream=File.OpenText(filePath); string tmpStr=tmpStream.ReadToEnd(); tmpStream.Close(); rs=GetDataTableFromString(tmpStr); tmpStr=""; } return rs; } /// <summary> /// 将指定Html字符串的数据转换成DataTable对象 --根据“<tr><td>”等特殊字符进行处理 /// </summary> /// <param name="tmpHtml">Html字符串</param> /// <returns></returns> private DataTable GetDataTableFromString(string tmpHtml) { string tmpStr=tmpHtml; DataTable TB=new DataTable(); //先处理一下这个字符串,删除第一个<tr>之前合最后一个</tr>之后的部分 int index=tmpStr.IndexOf("<tr"); if(index>-1) tmpStr=tmpStr.Substring(index); else return TB; index=tmpStr.LastIndexOf("</tr>"); if(index>-1) tmpStr=tmpStr.Substring(0,index+5); else return TB; bool existsSparator=false; char Separator=Convert.ToChar("^"); //如果原字符串中包含分隔符“^”则先把它替换掉 if(tmpStr.IndexOf(Separator.ToString())>-1) { existsSparator=true; tmpStr=tmpStr.Replace("^","^$&^"); } //先根据“</tr>”分拆 string[] tmpRow=tmpStr.Replace("</tr>","^").Split(Separator); for(int i=0;i<tmpRow.Length-1;i++) { DataRow newRow=TB.NewRow(); string tmpStrI=tmpRow[i]; if(tmpStrI.IndexOf("<tr")>-1) { tmpStrI=tmpStrI.Substring(tmpStrI.IndexOf("<tr")); if(tmpStrI.IndexOf("display:none")<0||tmpStrI.IndexOf("display:none")>tmpStrI.IndexOf(">")) { tmpStrI=tmpStrI.Replace("</td>","^"); string[] tmpField=tmpStrI.Split(Separator); for(int j=0;j<tmpField.Length-1;j++) { tmpField[j]=RemoveString(tmpField[j],"<font>"); index=tmpField[j].LastIndexOf(">")+1; if(index>0) { string field=tmpField[j].Substring(index,tmpField[j].Length-index); if(existsSparator) field=field.Replace("^$&^","^"); if(i==0) { string tmpFieldName=field; int sn=1; while(TB.Columns.Contains(tmpFieldName)) { tmpFieldName=field+sn.ToString(); sn+=1; } TB.Columns.Add(tmpFieldName); } else { newRow[j]=field; } }//end of if(index>0) } if(i>0) TB.Rows.Add(newRow); } } } TB.AcceptChanges(); return TB; } /// <summary> /// 从指定Html字符串中剔除指定的对象 /// </summary> /// <param name="tmpHtml">Html字符串</param> /// <param name="remove">需要剔除的对象--例如输入"<font>"则剔除"<font ???????>"和"</font>>"</param> /// <returns></returns> public string RemoveString(string tmpHtml,string remove) { tmpHtml=tmpHtml.Replace(remove.Replace("<","</"),""); tmpHtml=RemoveStringHead(tmpHtml,remove); return tmpHtml; } /// <summary> /// 只供方法RemoveString()使用 /// </summary> /// <returns></returns> private static string RemoveStringHead(string tmpHtml,string remove) { //为了方便注释,假设输入参数remove="<font>" if(remove.Length<1) return tmpHtml;//参数remove为空:不处理返回 if((remove.Substring(0,1)!="<")||(remove.Substring(remove.Length-1)!=">")) return tmpHtml;//参数remove不是<?????>:不处理返回 int IndexS=tmpHtml.IndexOf(remove.Replace(">",""));//查找“<font”的位置 int IndexE=-1; if(IndexS>-1) { string tmpRight=tmpHtml.Substring(IndexS,tmpHtml.Length-IndexS); IndexE=tmpRight.IndexOf(">"); if(IndexE>-1) tmpHtml=tmpHtml.Substring(0,IndexS)+tmpHtml.Substring(IndexS+IndexE+1); if(tmpHtml.IndexOf(remove.Replace(">",""))>-1) tmpHtml=RemoveStringHead(tmpHtml,remove); } return tmpHtml; } /// <summary> /// 将指定Excel文件中读取第一张工作表的名称 /// </summary> /// <param name="filePath"></param> /// <returns></returns> private string GetSheetName(string filePath) { string sheetName=""; System.IO.FileStream tmpStream=File.OpenRead(filePath); byte[] fileByte=new byte[tmpStream.Length]; tmpStream.Read(fileByte,0,fileByte.Length); tmpStream.Close(); byte[] tmpByte=new byte[]{Convert.ToByte(11),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0), Convert.ToByte(11),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0),Convert.ToByte(0), Convert.ToByte(30),Convert.ToByte(16),Convert.ToByte(0),Convert.ToByte(0)}; int index=GetSheetIndex(fileByte,tmpByte); if(index>-1) { index+=16+12; System.Collections.ArrayList sheetNameList=new System.Collections.ArrayList(); for(int i=index;i<fileByte.Length-1;i++) { byte temp=fileByte[i]; if(temp!=Convert.ToByte(0)) sheetNameList.Add(temp); else break; } byte[] sheetNameByte=new byte[sheetNameList.Count]; for(int i=0;i<sheetNameList.Count;i++) sheetNameByte[i]=Convert.ToByte(sheetNameList[i]); sheetName=System.Text.Encoding.Default.GetString(sheetNameByte); } return sheetName; } /// <summary> /// 只供方法GetSheetName()使用 /// </summary> /// <returns></returns> private int GetSheetIndex(byte[] FindTarget,byte[] FindItem) { int index=-1; int FindItemLength=FindItem.Length; if(FindItemLength<1) return -1; int FindTargetLength=FindTarget.Length; if((FindTargetLength-1)<FindItemLength) return -1; for(int i=FindTargetLength-FindItemLength-1;i>-1;i--) { System.Collections.ArrayList tmpList=new System.Collections.ArrayList(); int find=0; for(int j=0;j<FindItemLength;j++) { if(FindTarget[i+j]==FindItem[j]) find+=1; } if(find==FindItemLength) { index=i; break; } } return index; } #endregion }
泡泡龙 2014-08-02
  • 打赏
  • 举报
回复
学会vba这些就都会了
iiiu_2863645440 2014-08-02
  • 打赏
  • 举报
回复
读取Excel数据表数据到指定文本文件实例 private void btn_Txt_Click(object sender, EventArgs e) { //连接Excel数据库 OleDbConnection olecon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txt_Path.Text + ";Extended Properties=Excel 8.0"); olecon.Open();//打开数据库连接 OleDbDataAdapter oledbda = new OleDbDataAdapter("select * from [" + cbox_SheetName.Text + "$]", olecon);//从工作表中查询数据 DataSet myds = new DataSet();//实例化数据集对象 oledbda.Fill(myds);//填充数据集 StreamWriter SWriter = new StreamWriter(cbox_SheetName.Text + ".txt", false, Encoding.Default);//实例化写入流对象 string P_str_Content = "";//存储读取的内容 for (int i = 0; i < myds.Tables[0].Rows.Count; i++)//遍历数据集中表的行数 { for (int j = 0; j < myds.Tables[0].Columns.Count; j++)//遍历数据集中表的列数 { P_str_Content += myds.Tables[0].Rows[i][j].ToString() + " ";//记录当前遍历到的内容 }//CodeGo.net/ P_str_Content += Environment.NewLine;//字符串换行 } SWriter.Write(P_str_Content);//先文本文件中写入内容 SWriter.Close();//关闭写入流对象 SWriter.Dispose();//释放写入流所占用的资源 MessageBox.Show("已经将" + cbox_SheetName.Text + "工作表中的数据成功写入到了文本文件中", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); }
Ptrtoptr 2014-08-01
  • 打赏
  • 举报
回复
楼上能留下来一个方法给我贴一下.
devmiao 2014-08-01
  • 打赏
  • 举报
回复
最近研究了ASP.NET如何高效读取EXCEL文件,现总结如下: 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的获取, 再在项目中添加引用该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); 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(); }
wind_cloud2011 2014-08-01
  • 打赏
  • 举报
回复
http://wenku.baidu.com/view/3c1d9d8ad0d233d4b14e698e.html
wind_cloud2011 2014-08-01
  • 打赏
  • 举报
回复
以数据库方式查询数据: System.Data.OleDb.OleDbConnection objConn = new System.Data.OleDb.OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/excell.xls" + ";Extended Properties=Excel 8.0;"); ds = new DataSet(); OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", objConn); try { da.Fill(ds); } catch (Exception ex) { MessageBox.Show(ex.Message); objConn.Close(); return; } dataGridView1.DataSource = ds.Tables[0]; objConn.Close();
li_rui_1220 2014-08-01
  • 打赏
  • 举报
回复
我就需要创建Excel,数据写入,查询。标题栏设置,分页设置。 谢谢啦
moonwrite 2014-08-01
  • 打赏
  • 举报
回复
NOPI http://www.cnblogs.com/Areas/archive/2012/06/26/2563139.html
Sitrone 2014-08-01
  • 打赏
  • 举报
回复
资料确实很多,而且楼主问的目的性也不明确 随便一搜就有 http://www.cnblogs.com/Tsong/archive/2013/02/21/2920941.html
li_rui_1220 2014-08-01
  • 打赏
  • 举报
回复
我是菜鸟级别的,注释多一点的啊!
exception92 2014-08-01
  • 打赏
  • 举报
回复

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧