简体   繁体   English

使用 C# 中的 Excel 文件

[英]Working with Excel files in C#

I have Excel files that are in 2000 & 2003 format.我有 2000 和 2003 格式的 Excel 文件。 I need to import them via C# code into an access DB.我需要通过 C# 代码将它们导入访问数据库。 I have written a method to read the file into a data table.我已经编写了一种将文件读入数据表的方法。 No matter which connection string i use (I have checked the other posts on this topic) I continue to get "Table is not in the correct format" error.无论我使用哪个连接字符串(我已经检查了有关此主题的其他帖子),我都会继续收到“表格格式不正确”错误。 Can someone please explain to me what I am doing wrong.有人可以向我解释我做错了什么。

        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;
        }

Go through this code example carefully and try to understand the work flow. Go 仔细通过此代码示例并尝试了解工作流程。 You will get it real easy to write any kind programs for accessing excel data according to your requirements.根据您的要求,您将可以轻松编写任何类型的程序来访问 excel 数据。

1.Here I just have a Upload Field in order to select the Excel File in.aspx file 1.这里我只有一个Upload Field为了select Excel File in.aspx文件

<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>
  1. Now lets see what happens in code behind file (.aspx.cs file)现在让我们看看代码隐藏文件(.aspx.cs 文件)中发生了什么

protected void Upload_Button_Click(object sender, EventArgs e) { string connectionString = ""; protected void Upload_Button_Click(object sender, EventArgs e) { string connectionString = ""; if (Upload_File.HasFile) // checking whether file is selected to be uploaded 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 ");
                }
            }

Step by Step Explanation:分步说明:

  • We get the file name, extension, location.我们得到文件名、扩展名、位置。
  • And check it is the type (.xls or.xlsx - particularly for excels of 2003 or other formats).并检查它的类型(.xls 或.xlsx - 特别是对于 2003 或其他格式的 excel)。
  • Set connection strings according to the previous step.根据上一步设置连接字符串。
  • Open oledb connection打开oledb连接
  • Create the necessary data adapter and data table创建必要的数据适配器和数据表
  • open the connection打开连接
  • store the current table( where the data from excel is stored) in a datatable instance将当前表(excel 中的数据存储在其中)存储在数据表实例中
  • Store the name of the sheet in astring by getting it from the current table通过从当前表中获取工作表的名称,将其存储在字符串中
  • Fill the data adapter object(dAdapter) with the our data table (dtExcelRecords)用我们的数据表(dtExcelRecords)填充数据适配器对象(dAdapter)
  • close the connection关闭连接
  • Set datasource for the grid as out data table.将网格的数据源设置为输出数据表。
  • Bind it with our grid.将它与我们的网格绑定。

...And We are done! ......我们完成了!

Hope it helps.希望能帮助到你。

Try this尝试这个

OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;Extended Properties="Excel 8.0;HDR=Yes;IMEX=1";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM