日期:2014-05-17  浏览次数:20842 次

c# WINFRM 导出EXCEL
   想直接把datagridview里面的数据导出EXCEL,会的大神帮忙解答下,谢谢!

------解决方案--------------------
要看导多少行,行数很多,我试过8K行以上通过一行一行的赋值会报错。好像是COM超时。行数过多,用rang的Value2
        public void dgvToExcel(string s_FileName, DataGridView dgv)
        {
            Excel.Application m_xlsApp = null;
            Excel.Workbook m_Workbook = null;
            Excel.Worksheet m_Worksheet = null;
            object objOpt = System.Reflection.Missing.Value;
            System.Threading.Thread.CurrentThread.CurrentCulture = ci;
            m_xlsApp = new Excel.Application();

            try
            {
                m_Workbook = m_xlsApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
                m_Worksheet = (Excel.Worksheet)m_Workbook.Worksheets.get_Item(1);

                foreach (DataGridViewColumn dgvColumn in dgv.Columns)
                {
                    m_Worksheet.Cells[1, dgvColumn.Index + 1] = dgvColumn.HeaderText;
                }

                int i = 1;
                foreach (DataGridViewRow dgvRow in dgv.Rows)
                {
                    i++;
                    foreach (DataGridViewColumn dgvColumn in dgv.Columns)
                    {
                        Excel.Range range = (Excel.Range)m_Worksheet.Cells[i, dgvColumn.Index + 1];
                        range.NumberFormatLocal = "@";
                        m_Worksheet.Cells[i, dgvColumn.Index + 1] = staticMethodClass.ToStringAndTrim(dgvRow.