C# 读取Excel数据到datagridview中
要做Excel文档读取到datagridview单元格中的程序,
1.开始的时候尝试将Excel文档数据直接读取到datagridview单元格中,发现最后datagridview中存在很多空白行,且没办法对空白行进行处理
2.后来我通过先将Excel数据读取到二维数组中,再由二维数组转换成datatable类型数据,最后将datatable赋值给datagridview空间的datasource来实现,但现在出现一个新的问题,老是出现报错提示"异常来自 HRESULT:0x800A03EC";另外说一句我装的是Office2010专业版_试用版
具体代码如下:
using Microsoft.Office.Core;
using MSExcel = Microsoft.Office.Interop.Excel;
using MSWord = Microsoft.Office.Interop.Word;
private string path;
private MSExcel.Application excelApp;
private MSExcel.Workbooks wbs = null;
private MSExcel.Sheets sheet = null;
private MSExcel.Worksheet ws = null;
private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr;
string[,] str;
string[] strText=new string[4]{"宠物名称","天生技能1","天生技能2","天生技能3"};
OpenFileDialog open = new OpenFileDialog();
open.Title = "打开Excel文件";
open.Filter = "Excel文件(*.xlsx)|*.xlsx|所有文件(*.*)|*.*";
open.RestoreDirectory = true;
if (open.ShowDialog() == DialogResult.OK)
{
path = open.FileName;
str = readExcel(path);
for (int i = 0; i < strText.Length; i++)
{
dt.Columns.Add(strText[i].ToString());
}
for (int i = 0; i < str.GetLength(0); i++)
{
dr = dt.NewRow();
for (int j = 0; j < str.GetLength(1); j++)