-2

我想将 Excel 文件导入 Access 表。

我有一个第一次运行良好的代码。它正在遍历excel文件的所有工作表,并插入记录。

在第二次,我得到一个例外:

“表已经存在”

我知道该表已经存在于Access文件中!我想在上面插入更多记录!我不想放下它!

任何人都知道如何解决这个问题?

这是代码:

      class Program
{
    static void Main(string[] args)
    {

        string ExcelFiles = System.Configuration.ConfigurationSettings.AppSettings["FilesLocation"];
        string AccessFile = System.Configuration.ConfigurationSettings.AppSettings["AccessFileLocation"];

        string[] files = Directory.GetFiles(ExcelFiles, "*.xlsx");

        foreach (string excelFile in files)
        {

                string[] sheets = ListSheetInExcel(excelFile).ToArray();

                foreach (string sheetName in sheets)
                {

                    ImportSpreadsheet(
                        excelFile,
                        sheetName.Replace("'", ""),
                        "MyTable",
                       AccessFile);

                }

        }

    }


    public static void ImportSpreadsheet(string ExcelfileName, string ExcelsheetName, string AccesstableName, string AccessDatabase)
    {
        OleDbConnectionStringBuilder sbConnection = new OleDbConnectionStringBuilder();
        String strExtendedProperties = String.Empty;
        sbConnection.DataSource = ExcelfileName;
        if (Path.GetExtension(ExcelfileName).Equals(".xls"))//for 97-03 Excel file
        {
            sbConnection.Provider = "Microsoft.Jet.OLEDB.4.0";
            strExtendedProperties = "Excel 8.0;HDR=Yes;IMEX=1";//HDR=ColumnHeader,IMEX=InterMixed
        }
        else if (Path.GetExtension(ExcelfileName).Equals(".xlsx"))  //for 2007 Excel file
        {
            sbConnection.Provider = "Microsoft.ACE.OLEDB.12.0";
            strExtendedProperties = "Excel 12.0;HDR=Yes;IMEX=1";
        }
        sbConnection.Add("Extended Properties", strExtendedProperties);


        using (OleDbConnection conn = new OleDbConnection(sbConnection.ToString()))
        {
            try
            {
                conn.Open();
                using (OleDbCommand cmd = new OleDbCommand())
                {
                    cmd.CommandText = @"SELECT * INTO [MS Access;Database="
                        + AccessDatabase + "].["
                        + AccesstableName + "] FROM ["
                        + ExcelsheetName + "]";

                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = conn;
                    cmd.ExecuteNonQuery(); //THE ERROR OCCURS HERE !!!!!!!!
                }
            }
            catch (DbException ex)
            {
                Console.WriteLine("Exception: {0}\r\n   Stack Trace: {1}", ex.Message, ex.StackTrace);
            }
            finally
            {
                conn.Close();
            }
        }
    }


    public static List<string> ListSheetInExcel(string filePath)
    {
        OleDbConnectionStringBuilder sbConnection = new OleDbConnectionStringBuilder();
        String strExtendedProperties = String.Empty;
        sbConnection.DataSource = filePath;
        if (Path.GetExtension(filePath).Equals(".xls"))//for 97-03 Excel file
        {
            sbConnection.Provider = "Microsoft.Jet.OLEDB.4.0";
            strExtendedProperties = "Excel 8.0;HDR=Yes;IMEX=1";//HDR=ColumnHeader,IMEX=InterMixed
        }
        else if (Path.GetExtension(filePath).Equals(".xlsx"))  //for 2007 Excel file
        {
            sbConnection.Provider = "Microsoft.ACE.OLEDB.12.0";
            strExtendedProperties = "Excel 12.0;HDR=Yes;IMEX=1";
        }
        sbConnection.Add("Extended Properties", strExtendedProperties);

        List<string> listSheet = new List<string>();
        using (OleDbConnection conn = new OleDbConnection(sbConnection.ToString()))
        {
            conn.Open();
            DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

            foreach (DataRow drSheet in dtSheet.Rows)
            {
                if (drSheet["TABLE_NAME"].ToString().Contains("$"))//checks whether row contains '_xlnm#_FilterDatabase' or sheet name(i.e. sheet name always ends with $ sign)
                {
                    listSheet.Add(drSheet["TABLE_NAME"].ToString());
                }
            }
        }
        return listSheet;
    }
}
4

1 回答 1

1

我找到了解决方案。

命令“INSERT INTO”需要创建一个新表。

解决方案是构建一个不需要该命令的命令:

 cmd.CommandText = @"INSERT INTO [MS Access;Database="
                        + AccessDatabase + "].["
                        + AccesstableName + "] SELECT * FROM ["
                        + ExcelsheetName + "]";
于 2013-01-16T12:23:22.677 回答