关闭

Excel导出

标签: 数据excel导出
187人阅读 评论(0) 收藏 举报
分类:
   #region 将数据导出至Excel
        public void ExportToExcel(System.Data.DataTable dtTemp)
        {

            System.Windows.Forms.SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog();
            dlg.Filter = "Excel files (*.xls)|*.xls";
            dlg.FilterIndex = 0;
            dlg.RestoreDirectory = true;
            dlg.CreatePrompt = true;
            dlg.Title = "保存为Excel文件";
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Stream myStream;
                myStream = dlg.OpenFile();
                StreamWriter sw = new StreamWriter(myStream, System.Text.ASCIIEncoding.GetEncoding(-0));
                string columnTitle = "";
                //string columnTitle = "序号";
                try
                {
                    //for (int i = 0; i < dtTemp.Columns.Count; i++)
                    //{
                    //    columnTitle += "\t";
                    //    columnTitle += dtTemp.Columns[i].ColumnName.ToString();
                    //}
                    //sw.WriteLine(columnTitle);
                    for (int i = 0; i < dtTemp.Columns.Count; i++)
                    {
                       // columnTitle += "\t";
                        columnTitle += dtTemp.Columns[i].ColumnName.ToString();
                        columnTitle += "\t";
                    }
                    sw.WriteLine(columnTitle);

                    for (int j = 0; j < dtTemp.Rows.Count; j++)
                    {
                        string columnValue = "";
                    //    string columnValue = (j + 1).ToString();

                        for (int k = 0; k < dtTemp.Columns.Count; k++)
                        {
                          //  columnValue += "\t";

                            if (dtTemp.Rows[j][k].ToString() == "")
                            {

                                columnValue += "";
                            }
                            else
                            {
                                columnValue += dtTemp.Rows[j][k].ToString();
                            }
                            columnValue += "\t";
                        }
                        sw.WriteLine(columnValue);
                    }
                    sw.Close();
                    myStream.Close();
                    System.Windows.Forms.MessageBox.Show("导出成功!", "提示");

                }
                catch (Exception e)
                {
                    System.Windows.Forms.MessageBox.Show(e.ToString());
                }
                finally
                {
                    sw.Close();
                    myStream.Close();
                }
            }
        }
        #endregion
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:72332次
    • 积分:2274
    • 等级:
    • 排名:第16685名
    • 原创:140篇
    • 转载:140篇
    • 译文:0篇
    • 评论:7条
    最新评论