关闭

操作EXCEL(2)

1383人阅读 评论(3) 收藏 举报

ADO.net方式

OleDbConnection objConn = new OleDbConnection(
    "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strSampleFolder +
    "new.xls;Extended Properties=Excel 8.0;");
   objConn.Open();

   // Add two records to the table named 'MyTable'.
   OleDbCommand objCmd = new OleDbCommand();
   objCmd.Connection = objConn;
   objCmd.CommandText = "CREATE TABLE MyTable2 (FirstName char(255),LastName char(255))";
   objCmd.ExecuteNonQuery();
   
//   objCmd.CommandText = "Insert into MyTable (FirstName, LastName)" +
//    " values ('shao', 'zhidong')";
//   objCmd.ExecuteNonQuery();
//   objCmd.CommandText = "Insert into MyTable (FirstName, LastName)" +
//    " values ('张', '三')";
//   objCmd.ExecuteNonQuery();


   // Close the connection.
   objConn.Close();

自动化方式

// Start a new workbook in Excel.
   objExcel = new Excel.Application();
   objBooks = (Excel.Workbooks)objExcel.Workbooks;
   objBook = (Excel._Workbook)(objBooks.Add(objOpt));

   // Add data to cells of the first worksheet in the new workbook.
   objSheets = (Excel.Sheets)objBook.Worksheets;
   objSheet = (Excel._Worksheet)(objSheets.get_Item(1));
   objRange = objSheet.get_Range("A1", objOpt);
   objRange.set_Value(objOpt,"Last Name");
   objRange = objSheet.get_Range("B1", objOpt);
   objRange.set_Value(objOpt,"First Name");
   objRange = objSheet.get_Range("A2", objOpt);
   objRange.set_Value(objOpt,"shao");
   objRange = objSheet.get_Range("B2", objOpt);
   objRange.set_Value(objOpt,"zhidong");

   // Apply bold to cells A1:B1.
   objRange = objSheet.get_Range("A1", "B1");
   objFont = objRange.Font;
   objFont.Bold=true;

   // Save the workbook and quit Excel.
   objBook.SaveAs(strSampleFolder + "Book1.xls", objOpt, objOpt,
    objOpt, objOpt, objOpt, Excel.XlSaveAsAccessMode.xlNoChange,
    objOpt, objOpt, objOpt, objOpt, objOpt);
   objBook.Close(false, objOpt, objOpt);
   objExcel.Quit();

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:51093次
    • 积分:774
    • 等级:
    • 排名:千里之外
    • 原创:18篇
    • 转载:18篇
    • 译文:4篇
    • 评论:14条
    最新评论