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

C#导出Excel速度慢的解决方案
C#导出Excel速度奇慢,大概要5分钟时间,这个怎么解决

------解决方案--------------------
测试导出速度超快滴:
源码:
C# code

        private void toolStripLabel4_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl文件(*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "数据视图导出EXCEL文件"; 
            saveFileDialog.ShowDialog();
            Stream myStream;
            myStream = saveFileDialog.OpenFile();
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("utf-8"));
            string str = "";
            DateTime start = DateTime.Now;
            try
            {
                //写标题
                for (int i = 0; i < dataGridView1.ColumnCount; i++)
                {
                    if (i > 0)
                    {
                        str += "\t";
                    }
                    str += dataGridView1.Columns[i].HeaderText;
                }
                sw.WriteLine(str);

                //写内容
                 for (int j = 0; j < dataGridView1.Rows.Count; j++)
                 {
                     string tempStr = "";
                     for (int k = 0; k < dataGridView1.Columns.Count; k++)
                     {
                         if (k > 0)
                         {
                             tempStr += "\t";
                         }
                         if (dataGridView1.Rows[j].Cells[k].Value == null)
                         {
                             tempStr += string.Empty;
                         }
                         else
                         {
                             tempStr += dataGridView1.Rows[j].Cells[k].Value.ToString();
                         }
                     }
                     sw.WriteLine(tempStr);                    
                 }
                 sw.Close();
                 myStream.Close();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                sw.Close();
                myStream.Close();
            }
            MessageBox.Show("将此工作表导出为excel共耗时:" + DateTime.Now.Subtract(start).TotalMilliseconds.ToString() + "毫秒");
        }