C # datatable data in memory will be exported to Excel (a method to export the file stream mode) [Reserved] ...

Original link: http://www.cnblogs.com/happylyyer/p/4276347.html

Technical points: 1 Create a file stream for writing the final document StreamWriter sw = new StreamWriter (fileName, false, Encoding.GetEncoding ( "gb2312"));

2. StringBuilder class composition data to excel file for inserting a long string,
sb.append (dt.rows [I] [J] .ToString () + "\ T");
Note that can not be missed "\ t "this is very important! Because c # "\ t" is equal Tab on the keyboard [friends can try: open a new txt and then enter a press Tab, enter 2 press Tab, enter 3 Press Tab to save, and then open the excel file to just saved txt file pull into the open you will find the original. Write 123 words will be in each cell, respectively. So just use the above "\ t" to link the pile of data out of the database, so a one-time lead in, and they will be filled in accordance with each cell! ]

Ado, directly on the code.

Need to reference:
a using the System.IO;

publicvoid WriteExcel(DataSet ds, string path)//其中path里要包含要创建的Excel文件的名称
        {
            try
            {
                StreamWriter sw =new StreamWriter(path, false,Encoding.GetEncoding("gb2312"));
                StringBuilder sb =new StringBuilder();
                for (int k =0; k < ds.Tables[0].Columns.Count; k++)
                {
                    sb.Append(ds.Tables[0].Columns[k].ColumnName.ToString() +"\t");
                }
                sb.Append(Environment.NewLine);

                for (int i =0; i < ds.Tables[0].Rows.Count; i++)
                {
                     for (int j =0; j < ds.Tables[0].Columns.Count; j++)
                    {
                        sb.append (ds.Tables [0] .Rows [I] [J] .ToString () + "\ T");
                    }
                    sb.append (Environment.NewLine); // after each write data line wrap
                }
                SW. the Write (sb.ToString ());
                sw.Flush ();
                sw.Close (); // release resources
                MessageBox.Show ( "Excel file has been generated specified!");
            }
            the catch (Exception EX)
            {
                MessageBox.Show ( ex.Message);
            }            
        }

Reproduced in: https: //www.cnblogs.com/happylyyer/p/4276347.html

Guess you like

Origin blog.csdn.net/weixin_30764883/article/details/94783614