日期:2014-05-18  浏览次数:21069 次

c#操作Excel 求救~~~~~
现在需要Excel导入导出功能,谁有现成的工程啊,
发我邮箱 shirry2000@tom.com
谢谢了~~~~~~~~

------解决方案--------------------
//读取Excel的数据
string strCmd = string.Empty;
conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='Excel 8.0;HDR=No';" + "Data Source= " + @"C:\Documents and Settings\Administrator\桌面\test.xls");
cmd = new OleDbCommand();
cmd.Connection = conn;


conn.Open();
strCmd = "create Table [Sheet1](";
foreach (DataColumn dc in ds.Tables["Test"].Columns)//假设数据已经填充至DataSet表Test
{
strCmd += "[" + dc.ColumnName + "] nvarchar(20),";
}
strCmd = strCmd.Trim().Substring(0, strCmd.Length - 1);
strCmd += ")";
cmd.CommandText = strCmd;

cmd.ExecuteNonQuery();

foreach (DataRow dr in ds.Tables["Test"].Rows)
{
if (dr.RowState != System.Data.DataRowState.Deleted)
{
strCmd = "insert into [Sheet1] values(";
foreach (DataColumn dc in ds.Tables["Test"].Columns)
{
strCmd += "'" + dr[dc.ColumnName].ToString() + "',";
}

strCmd = strCmd.Substring(0, strCmd.Length - 1);
strCmd += ")";

cmd.CommandText = strCmd;

cmd.ExecuteNonQuery();


}
}


------解决方案--------------------
//首先要添加 Com 里的 microsoft.Excel 11.0(或者其他版本的) 
Microsoft.Office.Interop.Excel.Application xApp = new Microsoft.Office.Interop.Excel.ApplicationClass();

xApp.Visible = true;
//得到WorkBook对象, 可以用两种方式之一: 下面的是打开已有的文件 
Microsoft.Office.Interop.Excel.Workbook xBook = xApp.Workbooks._Open(@"D:\a.xls",
Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
//xBook=xApp.Workbooks.Add(Missing.Value);//新建文件的代码 
//指定要操作的Sheet,两种方式: 

Microsoft.Office.Interop.Excel.Worksheet xSheet = (Microsoft.Office.Interop.Excel.Worksheet)xBook.Sheets[1];
//Excel.Worksheet xSheet=(Excel.Worksheet)xApp.ActiveSheet; 

//读取数据,通过Range对象 
Microsoft.Office.Interop.Excel.Range rng1 = xSheet.get_Range("A1", Type.Missing);
// Console.WriteLine(rng1.Value2);
rng1.Value2 = "1";

//读取,通过Range对象,但使用不同的接口得到Range 
Microsoft.Office.Interop.Excel.Range rng2 = (Microsoft.Office.Interop.Excel.Range)xSheet.Cells[3, 1];
//Console.WriteLine(rng2.Value2);
rng2.Value2 = "2";

//写入数据 
Microsoft.Office.Interop.Excel.Range rng3 = xSheet.get_Range("C6", Missing.Value);
rng3.Value2 = "Hello";
rng3.Interior.ColorIndex = 6; //设置Range的背景色 

//保存方式一:保存WorkBook 
xBook.SaveAs(@"D:\CData.xls",
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Microsoft.Office.Inte