C# Stream流方式匯入Excel,htm,txt,Doc

來源:互聯網
上載者:User

 /// <summary>
        /// 流方式匯出Excel
        /// </summary>
        /// <param name="dgv"></param>
        private void ExportToExcel(DataGridView dgv)
        {
            if (dgv.Rows.Count == 0)
            {
                MessageBox.Show("沒有資料可供匯出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            // 儲存對話方塊
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl檔案 (*.xls)|*.xls|Xml檔案 (*.xml)|*.xml|網頁檔案 (*.htm)|*.htm|網頁檔案 (*.html)|*.html|Doc檔案 (*.doc)|*.doc|文字檔 (*.txt)|*.txt|所有檔案 (*.*)|*.*";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "匯出檔案儲存路徑";//為Excel
            saveFileDialog.FileName = null;
            saveFileDialog.ShowDialog();

            string Path = saveFileDialog.FileName;
            //被點了"取消"
            if (Path.IndexOf(":") < 0)
            {
                return;
            }

            //獲得資料類型
            string type = Path.Substring(Path.IndexOf(".") + 1);
            if (type.Equals("doc", StringComparison.CurrentCultureIgnoreCase))
            {
                //object path = Path;
                //Object none = System.Reflection.Missing.Value;
                //try
                //{
                //    Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
                //    Microsoft.Office.Interop.Word.Document document = wordApp.Documents.Add(ref none, ref none, ref none, ref none);
                //    //建立表格
                //    Microsoft.Office.Interop.Word.Table table = document.Tables.Add(document.Paragraphs.Last.Range, dgv.Rows.Count + 1, dgv.Columns.Count, ref none, ref none);

                //    try
                //    {
                //        for (int i = 0; i < dgv.Columns.Count; i++)//設定標題
                //        {
                //            table.Cell(1, i + 1).Range.Text = dgv.Columns[i].HeaderText;
                //        }

                //        for (int i = 0; i < dgv.Rows.Count; i++)//填充資料
                //        {
                //            for (int j = 0; j < dgv.Columns.Count; j++)
                //            {
                //                table.Cell(i + 2, j + 1).Range.Text = dgv[j, i].Value.ToString();
                //            }
                //        }
                //        document.SaveAs(ref path, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none);
                //        document.Close(ref none, ref none, ref none);
                //        MessageBox.Show("資料已經成功匯出到:" + Path, "匯出完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //    }
                //    catch (Exception ex)
                //    {
                //        MessageBox.Show("檔案 " + Path + " 正由另一起程使用,/r/n請先關閉該進程!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //        return;
                //    }
                //    finally
                //    {
                //        wordApp.Quit(ref none, ref none, ref none);
                //    }
                //    return;
                //}
                //catch (Exception ex)
                //{
                //    MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //    return;
                //}
            }

            Stream myStream;
            try
            {
                myStream = saveFileDialog.OpenFile();
            }
            catch (Exception ex)
            {
                MessageBox.Show("檔案 " + Path + " 正由另一起程使用,/r/n請先關閉該進程!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
            string columnTitle = "";

            if (type.Equals("htm", StringComparison.CurrentCultureIgnoreCase) || type.Equals("html", StringComparison.CurrentCultureIgnoreCase))
            {
                //寫入欄位標題
                columnTitle += "<table align=/"center/" border=/"1px/"><tr>";
                for (int i = 0; i < dgv.ColumnCount; i++)
                {
                    columnTitle += "<td>";
                    columnTitle += dgv.Columns[i].HeaderText + "</td>";
                }

                //寫入列內容
                for (int j = 0; j < dgv.Rows.Count; j++)
                {
                    columnTitle += "</tr><tr>";
                    for (int k = 0; k < dgv.Columns.Count; k++)
                    {
                        columnTitle += "<td>";
                        if (dgv.Rows[j].Cells[k].Value == null)
                            columnTitle += "&nbsp;</td>";
                        else
                            columnTitle += dgv.Rows[j].Cells[k].Value.ToString().Trim() + "</td>";
                    }
                }
                columnTitle += "</tr></table>";
                try
                {
                    sw.WriteLine(columnTitle);
                }
                catch
                {
                    MessageBox.Show("檔案 " + Path + " 正由另一起程使用,/r/n請先關閉該進程!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                finally
                {
                    sw.Close();
                    myStream.Close();
                }
                MessageBox.Show("資料已經成功匯出到:" + Path, "匯出完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            try
            {
                //寫入欄位標題
                for (int i = 0; i < dgv.ColumnCount; i++)
                {
                    if (i > 0)
                    {
                        columnTitle += "/t";
                    }
                    columnTitle += dgv.Columns[i].HeaderText;
                }
                sw.WriteLine(columnTitle);

                //寫入列內容
                for (int j = 0; j < dgv.Rows.Count; j++)
                {
                    string columnValue = "";
                    for (int k = 0; k < dgv.Columns.Count; k++)
                    {
                        if (k > 0)
                        {
                            columnValue += "/t";
                        }
                        if (dgv.Rows[j].Cells[k].Value == null)
                            columnValue += "";
                        else
                            columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim();
                    }
                    sw.WriteLine(columnValue);
                }
                sw.Close();
                myStream.Close();
                MessageBox.Show("資料已經成功匯出到:" + Path, "匯出完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                sw.Close();
                myStream.Close();
            }
        }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.