我有2000年及以后的Excel文件。 2003格式。我需要通过C#代码将它们导入访问数据库。我写了一个方法来将文件读入数据表。无论我使用哪个连接字符串(我已经检查过这个主题的其他帖子)我继续得到“表格格式不正确”错误。有人可以向我解释我做错了什么。
public static DataSet ParseExcel(string excelFile)
{
string sheetName = Path.GetFileNameWithoutExtension(excelFile);
string excelQuery = @"SELECT * FROM [" + sheetName + "]";
string excelConnctionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "" + excelFile + "" +
@";Extended Properties=" + "" + @"Excel 8.0;HDR=Yes;" + "";
if(File.Exists(excelFile))
{
var myConnection = new OleDbConnection(excelConnctionString);
myConnection.Open();
var myCommand = new OleDbDataAdapter(excelQuery, excelConnctionString);
myCommand.TableMappings.Add("Table", "TestTable");
var dtSet = new DataSet();
myCommand.Fill(dtSet);
myConnection.Close();
return dtSet;
}
return null;
}
答案 0 :(得分:2)
仔细阅读此代码示例并尝试了解工作流程。根据您的要求,您可以轻松编写任何类型的程序来访问Excel数据。
1.我刚才有一个上传字段,以便在.aspx文件中选择Excel文件
<asp:FileUpload ID="Upload_File" runat="server" />
<asp:Button ID="Upload_Button" runat="server" Text="Upload" onclick="btnUpload_Click"/>
<asp:GridView ID="Gridview_Name" runat="server">
</asp:GridView>
protected void Upload_Button_Click(object sender,EventArgs e) { string connectionString =“”; if(Upload_File.HasFile)//检查是否选择上传文件
{
//getting name of the file
string fileName = Path.GetFileName(Upload_File.PostedFile.FileName);
//getting extension of the file (for checking purpose - which type .xls or .xlsx)
string fileExtension = Path.GetExtension(Upload_File.PostedFile.FileName);
string fileLocation = Server.MapPath("" + fileName); //exact location of the excel files
Upload_File.SaveAs(fileLocation);
//Check whether file extension is xls or xslx
if (fileExtension == ".xls")
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
//Create OleDB Connection and OleDb Command
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
//cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dtExcelRecords = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dtExcelRecords);
con.Close();
Gridview_Name.DataSource = dtExcelRecords;
GridView_Name.DataBind();
}
else
{
Response.Write("Please Select a File to extract data ");
}
}
分步说明:
......我们完成了!
希望它有所帮助。
答案 1 :(得分:0)
试试这个
OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;Extended Properties="Excel 8.0;HDR=Yes;IMEX=1";