C#DataGridView数据导出到Excel

使用C#将DataGridView中的数据导出到Excel文件 在上面的代码中,我们首先创建了一个Excel Application对象,然后创建了一个Workbook对象和一个Worksheet对象。然后,我们使用双重循环将DataGridView中的数据逐行逐列地写入Excel文件中。通过以上步骤,我们就可以将DataGridView中的数据导出到Excel文件中了。要使用这个方法,我们需要将DataGridView控件和要保存的文件路径作为参数传递给方法。接下来,我们需要创建一个方法来导出DataGridView中的数据。首先,我们需要确保在项目中引用了。 阅读详情

Winform-C#DataGridView数据导出到Excel

一、窗体设计:

在这里插入图片描述

二、源码:

using System;
using System.Data;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
namespace ExportExcel
{
    public partial class Form1 : Form
    {   
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            #region 自定义dt数据
            System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("姓名", typeof(string));
            dt.Columns.Add("年龄", typeof(int));
            dt.Columns["ID"].AutoIncrement = true;
            DataRow dr = dt.NewRow();
            dr["姓名"] = "赵一";
            dr["年龄"] = "18";
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr["姓名"] = "钱二";
            dr["年龄"] = "19";
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr["姓名"] = "孙三";
            dr["年龄"] = "20";
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr["姓名"] = "李四";
            dr["年龄"] = "21";
            dt.Rows.Add(dr);
            #endregion
            dataGridView1.DataSource = dt;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            ExportExcels(dataGridView1);
        }
        private void ExportExcels(DataGridView myDGV)
        {
            string saveFileName = "";
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xls";
            saveDialog.Filter = "Excel97-2003工作簿(*.xls)|*.xls|Excel工作簿(*.xlsx)|*.xlsx";
            saveDialog.ShowDialog();
            saveFileName = saveDialog.FileName;
            if (saveFileName.IndexOf(":") < 0) return; 
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象,可能电脑未安装Excel");
                return;
            }
            Workbooks workbooks = xlApp.Workbooks;
            Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            Worksheet worksheet = (Worksheet)workbook.Worksheets[1];//取得sheet1
            //写入标题
            for (int i = 0; i < myDGV.ColumnCount; i++)
            {
                worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText;
            }
            //写入数值
            for (int r = 0; r < myDGV.Rows.Count; r++)
            {
                for (int i = 0; i < myDGV.ColumnCount; i++)
                {
                    worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;
                }
                System.Windows.Forms.Application.DoEvents();
            }
            worksheet.Columns.EntireColumn.AutoFit();
            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
                }
            }
            xlApp.Quit();
            GC.Collect();
            MessageBox.Show("文件: " + saveFileName + " 保存成功", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}
C#实现将DataGridView中数据导出到Excel (附完整源码) 阅读详情

相关推荐

C# DataGridView数据导出到Excel的完整实现

本文还有配套的精品资源,点击获取 简介:本文详细介绍了如何使用C#语言将.NET框架中DataGridView控件的数据导出到Excel文件中。首先概述了导出过程的两个主要步骤:创建Excel工作簿并填充数据,接着详细解释了实现这些步骤的具体编程方法,包括创建Excel应用程序实例、创建工作簿、设置活动工作表以及遍历DataGridView来填充数据。最后,介绍了如何保存和...

weixin_29935511的博客 3707

将DataGridVIew数据导出到Excel中的两种方法

}catch (Exception ex){MessageBox.Show(ex.Message, “软件提示”);}finally{sw.Close();myStream.Close();}}#endregion#region 方法二/*public void setExcel(DataGridView dgv, string name){try{int colCount = dgv.Columns.GetColumnCount(DataGridViewElementStates.Visible);int

2401_83329402的博客 2576

git连接华为软件开发云

我用的是github客户端的git shell 连接。用git bash也可以github客户端下载地址:https://desktop.github.com/1.在华为软件开发云上创建代码仓库2.在本地创建密钥SSH密钥帮助文档公钥是代码托管服务(CodeHub)识别您的用户身份的一种认证方式,通过公钥,您可以将本地git项目与代码托管服务(CodeHub)建立联系, 然后您就可以很方便的将本地...

sigmeta的博客 2117

C#中DataGridView数据导出到Excel

最近在做一个小程序,需要将DataGridView中的数据导出到Excel中显示和保存。最开始用使用如下代码实现: SaveFileDialog dlg = new SaveFileDialog(); //实例化一个SaveFileDialog保存文件对话框 dlg.Filter = "Excel files (*.xls)|*.xls"; ...

weixin_30332241的博客 398

二阶锥松弛在配电网最优潮流计算中的应用(IEEE33节点配电网最优潮流算例matlab程序)(yalmip+cplex)

文献[7]建立了以支路潮流计算为基础的OPF模型,针对OPF中的非凸性约束,采用SOCR技术将其松弛为二阶锥约束,整个 OPF 模型则被转化为二阶锥规划( Second Order Cone Programming,SOCP)问题,对其求解可以得到全局最优解。其次结合辐射型配电网潮流特点建立支路潮流约束,并考虑配电网中的可控单元,包括分布式电源和离散、连续无功补偿装置,建立其出力约束,该模型为非凸非线性模型;式中,αj,t和βij,t分别为t时段内节点i电压的二次方和支路ij电流的二次方。

weixin_47365903的博客 1万+

从零开始:如何用STM32和MAX30100打造你的第一台智能心率监测设备

本文详细介绍了如何使用STM32微控制器和MAX30100传感器从零开始构建智能心率监测设备。涵盖硬件选择、电路设计、软件开发到心率算法实现的全过程,特别适合嵌入式开发新手和创客。通过OLED显示和蓝牙串口传输数据,打造低成本、高精度的心率检测仪,为健康监测项目提供实用解决方案。

7z8x2c4v6b9的博客 198

C# DataGridView数据导出Excel文件

前言: 博主在做项目的时候需要把数据库的数据用DataGridView展示,然后把展示的数据导出为Excel文件,很多时候我们做项目都会有一个下载文件的按钮,我们需要用微软的的接口,Microsoft.Office.Interop.Excel,我们需要导入这个引用对DataGridView数据进行处理,利用Microsoft.Office.Interop.Excel提供的类对数据进行导出。博主把具体的操作步骤写下来教大家使用!!!! 每日一遍,快乐就完事了 1.创建窗体文件并设计好界面 博主直接用的之前的

qq_46104786的博客 1万+

Multisim14.3中FPGA接口电路设计:原理图项目应用

深入讲解在multisim14.3环境下构建FPGA接口电路的方法,结合原理图设计与项目实践,展现multisim14.3强大的电路仿真能力,提升数字系统开发效率。

weixin_42578963的博客 1161

C# winform 直接导出DataGridView数据到Excel表格

前面博客已经写过两种方法,各有缺点,但是项目中是追求的完美,所以才有我现在这种方法,可以说这种方法接近完美。 引用:NPOI 添加引用:项目==》管理NUGet程序包 下载安装: 判断DataGridView是否有数据: private void buttonX26_Click(object sender, EventArgs e) { if (data...

心若静,风奈何 5997

【OpenCV】第二十三章: 图像特征检测之SURF、FAST、BRIEF、OBR算法

4、由于在检测特征点时是需要对图像中所有的像素点进行检测,然而图像中的绝大多数点都不是特征点,如果对每个像素点都进行上述的检测过程,那显然是种浪费,所以FAST采用一种进行非特征点判别的方法:首先对候选点的周围90度的点(1,9,5,13)四个点进行测试,而且是先测试1和9,如果它们两个符合阈值要求再测试5和13。继SIFT和SURF后,大家在特征点检测的速度上又进行了很多的改进尝试,但速度的提升效果都不是非常明显,直到FAST算法诞生,特征点检测的速度才有了一个质的飞跃。无法计算描述符的特征点将被删除。

因为热爱所以坚持 2164

Pytorch实现之SRGAN+CBAM的结构设计

在SRGAN的残差连接中加入了CBAM注意力机制,同时设计了四类损失来训练。

LJ1147517021的博客 581

C# WinForm程序中将DataGridView中的数据导出为EXCEL

这是一种最简单的一种导表的方法。 步骤如下: 1、添加 Microsoft.Office.Interop.Excel的引用。 2、添加下面的方法到你的类中:         ///         /// 将DataGridView控件中数据导出到Excel         ///         /// DataGridView对象         /// 是否显示Excel

wangganggang90的专栏 1843

SAP_SD模块销售开票计划预收款系统配置及前台操作说明

在 SAP SD 中,开票计划(Billing Plan)是一种允许根据时间节点或里程碑对销售订单进行分期开票的功能。其中最常见的一种应用就是预收款(Down Payment Billing),即在销售订单中直接定义某个百分比或金额作为预收款,系统在开票时自动生成预收账单。大额合同或长期项目型销售(先收 20%,交货前收 30%,交货后收 50%)。分期付款模式(分阶段收款)。必须预收款才能安排生产或交货的业务。后台路径:SPRO—销售与分享—销售—销售凭证—销售凭证项目—定义项目类别。

我小时候很黑的博客 1420

C#dataGridView数据导出EXCEL

C#dataGridView数据导出EXCEL

tankoicq的专栏 637

使用OpenSSL创建多级CA证书链签发证书并导出为pkcs12/p12/pfx文件

文章目录1. 生成根CA证书并自签2. 生成二级CA证书并使用CA证书签发3. 生成服务器证书并使用二级CA证书签发4. 制作CA证书链5. 打包为p12文件6. 注意事项7. 使用`openssl x509`和`openssl ca`签发CA证书的差别 操作步骤: 生成根CA证书并自签 生成二级CA证书并使用CA证书签发 生成服务器证书并使用二级CA证书签发 制作CA证书链 打包为p12文件 1. 生成根CA证书并自签 # 创建root-ca并自签名 openssl req -x509 -newkey

Laurence的技术博客 9579

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

C#datagridview导出数据到excel

 添加dll引用右击选择你所在的项目的“引用”,选择“添加引用”。弹出“添加引用”对话框。选择“COM”选项卡。选择“Microsoft Excel 11.0 Object Library”单击“确定”按钮。代码public static bool ExportForDataGridview(DataGridView gridView, string fil

鹏程万里--扬帆起航 2397

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

C#DataGridview数据导出至excel两个方法

C#DataGridview数据导出至excel两个方法

HXD196的博客 3798

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

将C#datagridview控件的数据导出到Excel中

1.添加引用Microsoft.Office.Interop.Excel。 2.程序代码引用using Excel = Microsoft.Office.Interop.Excel; 3.控件事件代码:        string fileName = ""; string saveFileName = ""; SaveFileDial...

weixin_30877227的博客 159

C# winform 直接导出DataGridView数据到Excel表格的两种方法

DataGridView数据到Excel表格 方法一:利用微软的excel 操作类 引用:using Excel = Microsoft.Office.Interop.Excel; 缺点:速度慢 优点:Excel表格最前面的0不会去掉 首先给表格一个点击事件 private void buttonX26_Click(object sender, EventArgs e) { ...

心若静,风奈何 9312

C# DataGridView直接导出EXCEL 的两种方法

C# DataGridView直接导出EXCEL 的两种方法

qq_32066515的博客 3179

DataGridView数据导出到Excel

<br />此方法我感觉速度有点慢,但至今我只会这一种方法,记下来以备留用……<br /> <br />if (dataGridView1.Rows.Count != 0)//判断是否有数据<br />             {<br />                 SaveFileDialog saveas = new SaveFileDialog();<br />                 saveas.Title = "文件保存到";//弹出对话框的标题<br />       

飞 1040

把DatagridView中的数据导出到Excel中

private void ExportExcel(DataGridView dataGridViewControlName)//把DatagridView中的数据导出到Excel中,首先要添加引用 Microsoft.Office.Interop.Excel { if (dataGridViewControlName == null || dataGridV

michaellfd的专栏 653

DataGridview导出excel

这个方法需要使用的机器安装有microsoft office软件, using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Drawing; using System.Windows.Forms; using System.Data.SqlClient; u...

sappmis的博客 1316

c# winform DataGridView导出数据到Excel中,可以导出当前页和全部数据

<br /> 准备工作就是可以分页的DataGridView,和两个按钮,一个用来导出当前页数据到Excel,一个用来导出全部数据到Excel <br /><br />没有使用SaveFileDialog,但却可以弹出保存对话框来 <br /><br />先做导出当前页数据到Excel的 <br /><br />DataGridView命名为dataGridView1 <br /><br />C#代码  #region 导出当前页到Excel中     //按下导出按钮   private void but

539
上一篇: C#读取Excel到DataGridView(两种方式)
下一篇: C#输入日期获取对应的星期几
CSDNwhyu
博客等级 码龄7年 10粉丝 4原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值