標籤:
做作業的時候查了一點兒資料,用的vs2k5 讀 excel 2007發現用起來非常簡單。。。現在程式設計語言沒話說!1項目-添加引用-COM-Microsoft Excel 12.0 Object Library&& -Microsoft Office 12.0 Object Library2using Microsoft.Office.Core;using Microsoft.Office.Interop.Excel;using System.IO;using System.Reflection;3 string originalFile = System.Windows.Forms.Application.StartupPath + @".\a.xlsx"; string outputFile; SaveFileDialog save = new SaveFileDialog(); save.InitialDirectory = "D:\\"; save.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*"; save.FilterIndex = 1; save.RestoreDirectory = true; if (save.ShowDialog() == DialogResult.OK) { try { outputFile = save.FileName; System.IO.File.Copy(originalFile, outputFile, true); ExcelRS = new Microsoft.Office.Interop.Excel.ApplicationClass(); //開啟目標檔案outputFile RSbook = ExcelRS.Workbooks.Open(outputFile, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); //設定第一個工作溥 RSsheet = (Microsoft.Office.Interop.Excel.Worksheet)RSbook.Sheets.get_Item(1); //啟用當前工作溥 RSsheet.Activate(); RSsheet.Cells[1, 1] = dataGridView1.SelectedRows.Count; for (int i = 0; i < dataGridView1.SelectedRows.Count; ++i) { for (int j = 0; j < 11; ++j) { RSsheet.Cells[i + 2, j + 1] = dataGridView1.Rows[dataGridView1.SelectedRows[i].Index].Cells[j].Value.ToString().Trim(); // RSsheet.Cells RSsheet.get_Range(RSsheet.Cells[i + 2, j + 1], RSsheet.Cells[i + 2, j + 1]).EntireColumn.ColumnWidth = 40; //RSsheet.get_Range(RSsheet.Cells[i + 2, j + 1], missing).auto } } RSbook.Save(); ExcelRS.DisplayAlerts = true; ExcelRS.Visible = true; } catch (System.Exception ex) { MessageBox.Show(ex.Message); } finally { ExcelRS.Quit(); } }4 OpenFileDialog open = new OpenFileDialog(); open.InitialDirectory = @"D:\"; open.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*"; open.FilterIndex = 1; open.RestoreDirectory = true; if (open.ShowDialog() == DialogResult.OK) { try { ExcelRS = new Microsoft.Office.Interop.Excel.ApplicationClass(); RSbook = ExcelRS.Workbooks.Open(open.FileName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); RSsheet = (Microsoft.Office.Interop.Excel.Worksheet)RSbook.Sheets.get_Item(1); RSsheet.Activate(); Microsoft.Office.Interop.Excel.Range range = RSsheet.get_Range("A" + i, Type.Missing); counts = int.Parse(range.Text.ToString().Trim()); } catch (System.Exception ex) { MessageBox.Show(ex.Message); } finally { ExcelRS.Quit(); conn.Close(); } } 評論這張 轉寄至微博 轉寄至微博 閱讀(675)| 評論(0) | 用 “掃一掃”將文章分享到朋友圈。 用易信 “掃一掃”將文章分享到朋友圈。 喜歡 推薦 0人 | 轉載
Visual Studio 2005 C# 讀寫Excel檔案