简体   繁体   English

C#Winforms:Mysql数据库导出到Excel错误

[英]C# Winforms: Mysql Database export to Excel error

Hello again a have a last trouble with my application which is appear during export database to excel. 再次您好,我的应用程序遇到了最后一个问题,该问题在导出数据库到excel期间出现。 As you see codes below i used two different code block but unfortunetly after export process when i open the excel file it gives Error for both and doesn't open anything. 如您所见,下面的代码我使用了两个不同的代码块,但是不幸的是,在导出过程之后,当我打开excel文件时,这两个代码都给出了错误,并且没有打开任何东西。

Error Notification Window : The file may be corrupted or not working. 错误通知窗口 :文件可能已损坏或无法正常工作。 File format or extension does not match. 文件格式或扩展名不匹配。

For those code blocks i added Google Code project's Excel library to 'Referance' of my solution; 对于这些代码块,我在解决方案的“参考”中添加了Google Code项目的Excel库。

using ExcelLibrary.CompoundDocumentFormat;
using ExcelLibrary.SpreadSheet;
using ExcelLibrary.BinaryDrawingFormat;
using ExcelLibrary.BinaryFileFormat; 

// Original code block, first i used:

string myConnection = "datasource=root;port=root;username=root;password=root";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand cmdDataBase = new MySqlCommand("select name,surname,birth,telephone,email,city,adress,recorddate from doguAkdenizApp.team;", myConn);
try
{
    MySqlDataAdapter dataAdapter = new MySqlDataAdapter();
    dataAdapter.SelectCommand = cmdDataBase;
    dbdataset = new DataTable();
    dataAdapter.Fill(dbdataset);
    BindingSource bSource = new BindingSource();

    bSource.DataSource = dbdataset;
    dgvEkip.DataSource = bSource;
    dataAdapter.Update(dbdataset);

    DataSet dataSet = new DataSet("ekipDataset");
    dataSet.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
    dataAdapter.Fill(dbdataset);
    dataSet.Tables.Add(dbdataset);
    ExcelLibrary.DataSetHelper.CreateWorkbook("ekipDataset.xls", dataSet);
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

When code block above did not work i found this on internet but this block did not work well 当上面的代码块无法正常工作时,我在互联网上发现了此代码,但此代码块无法正常工作

string myConnection = "datasource=root;port=root;username=root;password=root";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand cmdDataBase = new MySqlCommand("select name,surname,birth,telephone,email,city,adress,recorddate from doguAkdenizApp.team;", myConn);

MySqlDataAdapter dataAdapter = new MySqlDataAdapter();
dataAdapter.SelectCommand = cmdDataBase;
dbdataset = new DataTable();
dataAdapter.Fill(dbdataset);
BindingSource bSource = new BindingSource();

bSource.DataSource = dbdataset;
dgvEkip.DataSource = bSource;
dataAdapter.Update(dbdataset);

dbdataset.WriteXml("Ekip_Dataset.xls"); //I am not sure why he used "WriteXml" but i tried as this 
MessageBox.Show("Dosya basariyla olusturulmustur.");

So what is the problem here or is there another way to export database to Excel? 那么,这里的问题是什么?或者还有另一种将数据库导出到Excel的方法吗? As well i am curious for how can i let user to choose where to save excel file? 以及我很好奇我如何让用户选择将Excel文件保存在哪里?

Please try below code: 请尝试以下代码:

    using FileExcel = Microsoft.Office.Interop.Excel;

    string sqlConnection = "Data Source=Enter here you db string");
    /// <summary>
    /// Function to write database content in excel sheet.
    /// </summary>
    /// <param name="tableName"></param>
    /// <param name="localFileName"></param>
    public void WriteDataToExcel(string tableName, string localFileName)
    {
        SqlConnection conn = new SqlConnection(sqlConnection);
        object misValue = System.Reflection.Missing.Value;
        FileExcel.Application xlApp = new FileExcel.Application();
        FileExcel.Workbook xlWorkBook = xlApp.Workbooks.Add(misValue); ;
        FileExcel.Worksheet xlWorkSheet = (FileExcel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        try
        {
            //Read data from database.
            conn.Open();
            SqlDataAdapter da = new SqlDataAdapter("select * from " + tableName + "", conn);
            DataSet ds = new DataSet();
            da.Fill(ds);
            string data = null;
            int headerRowTotal = 0;
            for (int i = 0; i < 1; i++)
            {
                for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                {
                    xlWorkSheet.Cells[i + 1, j + 1] = ds.Tables[0].Columns[j].ToString();
                }
                headerRowTotal++;
            }

            for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
            {
                for (int j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
                {
                    data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
                    xlWorkSheet.Cells[headerRowTotal + i + 1, j + 1] = data;
                }
            }
            //Check and delte file if already exist.
            if (File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), localFileName)))
            {
                //Delete file.
                File.Delete(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), localFileName));
            }
            xlWorkBook.SaveAs(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), localFileName), FileExcel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, misValue, misValue, FileExcel.XlSaveAsAccessMode.xlShared, FileExcel.XlSaveConflictResolution.xlUserResolution, true, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();
            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);
        }
        catch (Exception err)
        {
            MessageBox.Show(err.Message);
            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);
        }
    }

    /// <summary>
    /// Function to release object of excel files.
    /// </summary>
    /// <param name="obj"></param>
    private void releaseObject(object obj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch (Exception err)
        {
            obj = null;
            MessageBox.Show(err.Message);
        }
        finally
        {
            GC.Collect();
        }
    }

Put your connection string of database in variable "sqlConnection". 将数据库的连接字符串放在变量“ sqlConnection”中。

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

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