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

时间:2017-02-06 09:48:23

标签: c# mysql database excel import

再次问好我的应用程序的最后一个问题是在导出数据库中出现excel。当您看到下面的代码时,我使用了两个不同的代码块,但是在导出过程中我打开excel文件后不方便,它为两者提供了Error并且没有打开任何内容。

  

错误通知窗口:文件可能已损坏或无法正常工作。文件格式或扩展名不匹配。

对于那些代码块,我将Google Code项目的Excel库添加到我的解决方案的“Referance”中;

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

当上面的代码块无法正常工作时,我在互联网上找到了这个,但这个块效果不好

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.");

那么这里有什么问题,还是有另一种方法将数据库导出到Excel?我也很好奇我如何让用户选择保存excel文件的位置?

1 个答案:

答案 0 :(得分:0)

请尝试以下代码:

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

将数据库的连接字符串放在变量&#34; sqlConnection&#34;。