OleDbCommand olecommand = new OleDbCommand(str, new OleDbConnection(strConn));
OleDbDataAdapter oleadapter = new OleDbDataAdapter(olecommand);
DataSet mydataset = new DataSet();
oleadapter.Fill(mydataset, "[Sheet1$]");
this.dataGridVIEw1.DataSource = mydataset;
this.dataGridVIEw1.DataMember = "[sheet1$]";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
//需要添加 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&文章整理:學網 http://www.xue5.com (本站) [1] [2] [3]
quot;;
rng3.Interior.ColorIndex = 6; //設置Range的背景色
//保存方式一:保存WorkBook
xBook.SaveAs(@"D:\CData.xls",
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
////保存方式二:保存WorkSheet
//xSheet.SaveAs(@"D:\CData2.xls",
//Missing.Value, Missing.ValuMissing.Value, Missing.Value,
//Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
////保存方式三
//xBook.Save();
//xSheet = null;
//xBook = null;
//xApp.Quit(); //這一句是非常重要的,否則Excel對象不能從內存中退出
//xApp = null;