1、using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows.Forms;using Microsoft.Office.Interop.Excel;namespace ExcelToolspublic class ReadingAndwriting/ / 导出Excel/ / dataGridView控件名/ 路径名public static void WritingExcel(DataGridView gridView, string filenam
2、e)Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();Workbook book = app.Workbooks.Add(Type.Missing);Worksheet sheet = book.Worksheets1 as Worksheet;/sheet.Name = “student“;/遍历所有的列标题for (int i = 0; i / 导入Excel/ / dataGridView控件名/ 路径名public static void R
3、eadingExcel(DataGridView gridView, string fileName)Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();Workbook book = app.Workbooks.Open(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Mis
4、sing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);Worksheet sheet = book.Worksheets1 as Worksheet;gridView.Rows.Clear();gridView.Columns.Clear();/添加每一列的列标题for (int i = 1; ; i+)string value = (sheet.Cells1, i as Range).Text.ToString();/获得每列第一行数据。if (value = str
5、ing.Empty)/如果为空则代表已无数据break;gridView.Columns.Add(“, value);/导入每一行的数据for (int i = 2; ; i+)string value = (sheet.Cellsi, 1 as Range).Text.ToString();/获得每行第一列数据。if (value = string.Empty)/如果为空则代表已无数据break;/获得EXCEL中每行上的每列数据string ID = (sheet.Cellsi, 1 as Range).Text.ToString();string param1 = (sheet.Cell
6、si, 2 as Range).Text.ToString();string param2 = (sheet.Cellsi, 3 as Range).Text.ToString();string param3 = (sheet.Cellsi, 4 as Range).Text.ToString();string param4 = (sheet.Cellsi, 5 as Range).Text.ToString();string param5 = (sheet.Cellsi, 6 as Range).Text.ToString();string param6 = (sheet.Cellsi, 7 as Range).Text.ToString();gridView.Rows.Add(new object ID, param1, param2, param3, param4, param5, param6 );book.Close(Type.Missing, Type.Missing, Type.Missing);app.Workbooks.Close();app.Quit();注:以上为 c# VS2008的写法,c# VS2010 的写法把文中所有的(Type.Missing)去掉就行。