Excel导出

public static void ExportToExcel(DataTable dt)
        {
            //Excel名称   
            string str = "data_list" + ".xls";
            //  Excel保存的路径(项目中files文件夹下)
            using (StreamWriter sw = new StreamWriter(Application.StartupPath + "//out_data//" + str, false, Encoding.GetEncoding("gb2312")))
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    sb.Append(dt.Columns[i].ColumnName.ToString() + "\t");
                }
                sb.Append(Environment.NewLine);

                for (int r = 0; r < dt.Rows.Count; r++)
                {
                    System.Windows.Forms.Application.DoEvents();

                    for (int c = 0; c < dt.Columns.Count; c++)
                    {
                        sb.Append(dt.Rows[r][c].ToString() + "\t");
                    }
                    sb.Append(Environment.NewLine);
                }
                sw.Write(sb.ToString());
                sw.Flush();
                sw.Close();
            }
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); //引用Excel对象  
            Microsoft.Office.Interop.Excel.Workbook book = excel.Application.Workbooks.Add(Application.StartupPath + "//out_data//" + str);
            excel.Visible = true;
        }

其中     Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); //引用Excel对象  
            Microsoft.Office.Interop.Excel.Workbook book = excel.Application.Workbooks.Add(Application.StartupPath + "//out_data//" + str);
            excel.Visible = true;

是用来保存后打开excel文件,不需要可以删除

posted @ 2021-10-20 15:10  凉介-C  阅读(32)  评论(0编辑  收藏  举报