C#向excel中写入数据的三种方式

news/2024/7/21 3:58:30 标签: excel, c#, string, report, html
htmledit_views">

第一种:将DataGrid中的数据以流的形式写到html" title=excel>excel中,格式以html的形式存在

               

            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "GB2312";
            Response.AppendHeader("Content-Disposition", "attachment;filename=DialoutTemplate.xls");
            // 如果设置为 GetEncoding("GB2312");导出的文件将会出现乱码!!!
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "application/ms-html" title=excel>excel";//设置输出文件类型为html" title=excel>excel文件。

            //Response.ContentType = "application/vnd.ms-html" title=excel>excel";//输出类型
            //Response.Charset = "";
            //关闭 ViewState
            EnableViewState = false;
            System.IO.StringWriter tw = new System.IO.StringWriter();//将信息写入字符串
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);//在WEB窗体页上写出一系列连续的HTML特定字符和文本。
            //此类提供ASP.NET服务器控件在将HTML内容呈现给客户端时所使用的格式化功能
            //获取control的HTML
            dg.RenderControl(hw);//将table中的内容输出到HtmlTextWriter对象中
            // 把HTML写回浏览器
            Response.Write(tw.ToString());
            Response.Flush();
            Response.End();

 

第二种:将数据源中的数据以文件流的形式写到html" title=excel>excel中,格式以txt的形式存在

              

            FileStream fs = new FileStream(Server.MapPath("html" title=report>report_export/DialoutTemplate.xls"), FileMode.Create, FileAccess.Write);
            StreamWriter rw = new StreamWriter(fs, Encoding.Default);//建立StreamWriter为写作准备;
            DataTable dt = GetDataTableSource();
            int count = dt.Columns.Count;
            html" title=string>string head = "";
            html" title=string>string values = "";
            for (int i = 0; i < count; i++)
            {
                html" title=string>string h = dt.Columns[i].ColumnName + "\t";
                html" title=string>string v = dt.Rows[0][i].ToString() + "\t";
                head += h;
                values += v;
            }
            rw.WriteLine(head);
            rw.WriteLine(values);
            rw.Close();
            fs.Close();
            Response.Redirect("html" title=report>report_export/DialoutTemplate.xls");

 

第三种:将数据源中的数据直接写到html" title=excel>excel中,格式以xls形式存在,好处导出的

               数据可以直接导入,可以将数字格式自动转化为文本格式,可以减少

               格式转化的繁琐环节,还可以预留将数字转换为文本的格式的行数,

               可以完全自定义

 

                

            Excel.Application xlApp;
            Excel.Workbook xlBook;
            Excel.Workbooks xlBooks;
            //Excel.Range xlRange;
            Excel.Sheets xlsheets;
            Excel.Worksheet xlSheet;
            int k = 0;
            try
            {
                html" title=string>string strCurrentPath = Server.MapPath("html" title=report>report_export/DialoutTemplate.xls");
                html" title=string>string FilePath = strCurrentPath;
                FileInfo fi = new FileInfo(FilePath);
                if (fi.Exists)     //判断文件是否已经存在,如果存在就删除!
                {
                    fi.Delete();
                }
                xlApp = new Excel.Application();
                xlBooks = xlApp.Workbooks;
                xlBook = xlBooks.Add(Type.Missing);
                xlsheets = xlBook.Worksheets;
                IntPtr intptr = new IntPtr(xlApp.Hwnd);
                xlSheet = (Excel.Worksheet)xlsheets.get_Item(1);
                DataTable dt = GetDataTableSource();
                int count = dt.Columns.Count;
                for (int i = 0; i < count; i++)
                {
                    html" title=string>string h = dt.Columns[i].ColumnName;
                    html" title=string>string v = dt.Rows[0][i].ToString();
                    ((Excel.Range)xlSheet.Cells[1, i + 1]).Value2 = h;
                    Excel.Range r1 = xlSheet.get_Range(xlSheet.Cells[1, 1], xlSheet.Cells[1, i + 1]);
                    r1.NumberFormatLocal = "@";
                    ((Excel.Range)xlSheet.Cells[2, i + 1]).Value2 = v;
                    Excel.Range r2 = xlSheet.get_Range(xlSheet.Cells[2, 1], xlSheet.Cells[2, i + 1]);
                    r2.NumberFormatLocal = "@";
                }
                for (int j = 1; j < 500; j++)
                {
                    Excel.Range r = xlSheet.get_Range(xlSheet.Cells[2 + j, 1], xlSheet.Cells[2 + j, count]);
                    r.NumberFormatLocal = "@";
                }
                xlBook.SaveAs(FilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                xlBook.Close(false, Type.Missing, Type.Missing);
                xlBooks.Close();
                xlApp.Quit();
                Response.Redirect("html" title=report>report_export/DialoutTemplate.xls");
                GetWindowThreadProcessId(intptr, out k);
                System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
                p.Kill();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
            finally
            {
                //xlRange = null;
                xlSheet = null;
                xlBook = null;
                xlApp = null;
            }

 


http://www.niftyadmin.cn/n/1728018.html

相关文章

DLL_THREAD_DETACH 认识误区

DLL 里面使用TLS (Local Thread Storage ) 的常见做法是&#xff1a;在DLLMain的DLL_PROCESS_ATTACH/DLL_THREAD_ATTACH 被调用的时候为每个线程&#xff08;Thread&#xff09;分配内存&#xff0c;而在DLL_THREAD_DETACH/DLL_PROCESS_DETACH 被调用的时候释放内存。 MSDN文章…

安装eccodes运行代码出错解决

为了在Windows下读取grib文件&#xff0c;在Anaconda环境下安装了xarraycgribeccodes。参考WIndows下xarraycgrib读取grib文件。 在Anaconda下新建虚拟环境安装相应的依赖库&#xff0c;参考Windows下Anaconda的下载,安装与使用。程序在Prompt中正确运行。但在Pycharm中新建pr…

asp.net如何将页面Table控件中的数据写到excel中总结

我们在做报表统计的时候&#xff0c;在页面中放个服务器端的控件Table1 在cs代码中自动组合行和列 第一种情况&#xff1a;页面有两个按钮&#xff0c;分别为显示报表按钮和导出报表 显示报表按钮将组合成的table中的数据显示到界面上 导出报表按钮将已显示到界面table中的数…

Python学习:Python GIL(全局解释器锁)

在Python学习&#xff1a;Python并发编程之Futures中解释为什么多线程每次只能有一个线程执行&#xff1f;是由于GIL(全局解释器锁&#xff09;的存在&#xff0c;导致无论你启多少个线程&#xff0c;你有多少个cpu, Python在执行的时候会淡定的在同一时刻只允许一个线程运行。…

预编译头文件的使用

1、摘要 本文介绍VC6的预编译功能的使用&#xff0c;由于预编译详细使用比较的复杂&#xff0c;这里只介绍几个最重要的预编译指令: /Yu, /Yc,/Yx,/Fp。其它的详细资料可以参考 MSDN Compiler and Linker -> Details->Creating Precompiled Header files 2、关键字 预编译…

asp.net2003页面触发事件如何控制滚动条的位置

在页面aspx中<% Page language"c#" Codebehind"WorkManage_OrderHandleDetail.aspx.cs" AutoEventWireup"false" SmartNavigation"true" Inherits"standard_v5.WorkManage_OrderHandleDetail" %> 设置SmartNavigatio…

VC获取其他进程ListCtrl内容

VC读写其他进程ListCtrl数据到本进程的实例&#xff0c;下面用Windows任务管理器来做测试&#xff1a; 1、捕获窗口句柄&#xff1a; 用SPY可以看到如下父子窗口关系&#xff1a; 添加ListCtrl&#xff0c;设置style / Report、关联控件变量m_ListCtrl&#xff0c;再添加一个按…

Python学习:并发编程之Asyncio

在Python学习&#xff1a;Python并发编程之Futures学习了 Python 并发编程的一种实现——多线程。本博客继续学习 Python 并发编程的另一种实现方式——Asyncio。 在处理 I/O 操作时&#xff0c;使用多线程与普通的单线程相比&#xff0c;效率得到了极大的提高。多线程有诸多优…