に Excel テーブルをインポートしましたgridview
。自分のノートでは、すべて問題ありません。ただし、一部のノートブックでは、Excel セルが空に戻ります。私は使用ASP.NET 4.0
していますVisual C#
using System;
using System.Data.OleDb;
using System.Data;
using System.IO;
namespace ReadExcelInToDataSet
{
public partial class Default : System.Web.UI.Page
{
OleDbConnection oledbConn;
protected void Page_Load(object sender, EventArgs e)
{
try
{
string path = System.IO.Path.GetFullPath(Server.MapPath("~/Table_sverks.xls"));
if (Path.GetExtension(path) == ".xls")
{
oledbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
}
else if (Path.GetExtension(path) == ".xlsx")
{
oledbConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
}
oledbConn.Open();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter oleda = new OleDbDataAdapter();
DataSet ds = new DataSet();
cmd.Connection = oledbConn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [Sheet1$]";
oleda = new OleDbDataAdapter(cmd);
oleda.Fill(ds);
grvData.DataSource = ds.Tables[0];
grvData.DataBind();
}
catch (Exception ex)
{
lblError.Text = ex.ToString();
}
finally
{
oledbConn.Close();
}
}
}
}