[C#] 把DataTable寫入到Excel....第一版

  • 11613
  • 0
  • 2012-01-06

摘要:[C#] 把DataTable寫入到Excel....

        public void WriteToExcel(DataTable myDataTable, string s_fileName)
        {
            try
            {
                string tempImagePath = Application.StartupPath;//軟體安裝目錄
                string temp = tempImagePath + "\\Execl";//目錄下的Excel文件
                Directory.CreateDirectory(@temp);
                string strFilePath = @Application.StartupPath + @"\Execl\" + s_fileName + ".xls"; //賦予檔名
                System.IO.StreamWriter sw = new System.IO.StreamWriter(strFilePath, true, System.Text.Encoding.Default); //寫入資料流
                object[] values = new object[myDataTable.Columns.Count];

                for (int i = 0; i < myDataTable.Columns.Count; ++i)
                {
                    sw.Write(myDataTable.Columns[i].Caption.ToString());
                    sw.Write('\t');
                }

                sw.Write("\r\n");

                for (int i = 0; i < myDataTable.Rows.Count; i++)
                {
                    for (int j = 0; j < values.Length; ++j)
                    {
                        sw.Write(myDataTable.Rows[i][j].ToString());
                        sw.Write('\t');
                    }

                    sw.Write("\r\n");
                }

                sw.Flush();
                sw.Close();

                MessageBox.Show("成功匯出[" + myDataTable.Rows.Count.ToString() + "]行到Execl!");
            }
            catch (Exception ex)
            {
                MessageBox.Show("匯出Execl失敗!");
            }
        }

 

 






Y2J's Life:http://kimenyeh.blogspot.tw/