1:首先需要引用Microsoft.Office.Interop.Excel
Excel读写本实例是使用Office的组件:Microsoft.Office.Interop.Excel
首先需要引用office组件,如下图:
选择后,工程中引用就会出现组件。
2:读取Excel,将内容展示在窗体的DataGridView中。
private void ReadFromExcelFile()
{
string filePath = System.IO.Directory.GetCurrentDirectory() + "\\Example.xlsx";
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Workbook workbook = excel.Workbooks.Open(filePath);
Worksheet worksheet = workbook.Sheets[1];
Range range = worksheet.UsedRange;
int rowCount = range.Rows.Count;
int colCount = range.Columns.Count;
for (int i = 2; i <= rowCount; i++)
{
ExcelData readData = new ExcelData();
Type type = readData.GetType();
PropertyInfo[] property = type.GetProperties();
for (int j = 1; j <= colCount; j++)
{
string cellValue = (range.Cells[i, j] as Range).Value.ToString();
property[j - 1].SetValue(readData, cellValue, null);
}
ExcelDataList.Add(readData);
}
RefreshDgv();
// 关闭Excel对象
workbook.Close();
excel.Quit();
}
3:读取后可以将列表中内容保存到Excel文件中
private void WriteToExcel()
{
string filePath = System.IO.Directory.GetCurrentDirectory() + "\\WriteExample.xlsx";
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = false;//是打开不可见
Workbook workbook = excel.Workbooks.Add();
Worksheet worksheet = workbook.Sheets[1];
Type type = typeof(ExcelData);
PropertyInfo[] property = type.GetProperties();
int nColumn = property.Count();
int nRow = ExcelDataList.Count();
for (int j = 1; j <= nRow; j++)
{
ExcelData readData = ExcelDataList[j - 1];
Type typeData = readData.GetType();
PropertyInfo[] propertyData = typeData.GetProperties();
for (int i = 1; i <= nColumn; i++)
{
worksheet.Cells[j, i] = propertyData[i - 1].GetValue(readData, null);
}
}
excel.DisplayAlerts = false;
workbook.SaveAs(filePath);
workbook.Close();
excel.Quit();
MessageBox.Show("导出成功!");
}
代码很简单,可以给新手一点启发。可以关注gzh 爱学习的兔八哥,hf消息 Excel读写,可以获得源代码。