使用C#将数据导出到Excel中的问题

问题描述:

你好朋友,

我在C#中遇到了很大的问题.

我已经将数据网格"视图导出到Excel中,但是没有导出列名,并且我不知道如何导出列名.

我现在向您显示代码,如果您能告诉我我的错误在哪里...


Hello friends,

I have very big problem in C#.

I have Exported the Data Grid view into Excel but the column name is not exported and I don''t know how I can export the Column name.

I''m showing you the code now, if you could just tell me where my mistake is...


// code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data.OleDb;
using System.IO;
using MySql.Data.MySqlClient;
using System.Reflection;

namespace PolicySoft
{
    public partial class ExportDateWise : Form
    {
        
        private DataSet ds;

        public ExportDateWise()
        {
            InitializeComponent();
        }


        public void DataGridViewExport(String filepath)
        {
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            int i = 0;
            int j = 0;
            for (i = 0; i <= gv_show_dateWiseDetails.RowCount - 1; i++)
            {
                for (j = 0; j <= gv_show_dateWiseDetails.ColumnCount - 1; j++)
                {
                    DataGridViewCell cell = gv_show_dateWiseDetails[j, i];
                    xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;
                }
            }
            xlWorkBook.SaveAs(filepath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();
            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);
            MessageBox.Show("Export SuccessFully");
        }
        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);

                obj = null;
            }
            catch (Exception ex)
            {

                obj = null;

                MessageBox.Show("Exception Occured while releasing object " + ex.ToString());

            }
            finally
            {

                GC.Collect();
            }
        }

        private void btn2Excel_Click(object sender, EventArgs e)
        {

            saveFileDialog1.Filter = "Excel (*.xls)|*.xls";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if (!saveFileDialog1.FileName.Equals(String.Empty))
                {
                    FileInfo f = new FileInfo(saveFileDialog1.FileName);
                    if (f.Extension.Equals(".xls"))
                    {
                        DataGridViewExport(saveFileDialog1.FileName);
                    }
                    else
                    {
                        MessageBox.Show("Invalid file type");
                    }
                }
                else
                {
                    MessageBox.Show("You did pick a location to save file to");
                }
            }
        }
         
        private void btn_ok_Click(object sender, EventArgs e)
        {
            try
            {
                ds = new DataSet();
                MySqlConnection con1 = new MySqlConnection(StartUp.database);
                con1.Open();
                string str = "call ps_show_details_date_wise('" + dtp_fromDate.Value.ToString("yyyy-MM-dd") + "','" + dtp_toDate.Value.ToString("yyyy-MM-dd") + "')";
                MySqlDataAdapter da = new MySqlDataAdapter(str, con1);
                da.Fill(ds, "t_transaction");
                gv_show_dateWiseDetails.DataSource = ds.Tables[0];
                gv_show_dateWiseDetails.ReadOnly = true;
                con1.Close();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}


:(

您需要呈现列标题,类似于此处的示例

http://www.dotnetspark.com/kb/436-convert-datatable-to-csv-file-using-c-sharp.aspx [
You need to render the column headers, similar to the example here

http://www.dotnetspark.com/kb/436-convert-datatable-to-csv-file-using-c-sharp.aspx[^]

That is working with a data table + csv, but the principal is the same.

First, write the column names out from your source (DataTable, Gridview, whatever). Then iterate through each row.


嗨naim khan,


http://social.msdn.microsoft.com /forums/zh-CN/vbgeneral/thread/27a9002e-9d53-440d-9750-e6c64406fdd6/ [
Hi naim khan,


http://social.msdn.microsoft.com/forums/en-US/vbgeneral/thread/27a9002e-9d53-440d-9750-e6c64406fdd6/[^]

This link helpful to you and also you get any idea.

Your are missing a loop for add a column name from datagridview in before set a value.

Thanks.