方法一:

SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "Execl files (*.xls)|*.xls";
dlg.FilterIndex = 0;
dlg.RestoreDirectory = true;
dlg.CreatePrompt = true;
dlg.Title = "保存为Excel文件";
dlg.FileName = "不合格记录";//保存的Excel名字
if (dlg.ShowDialog() == DialogResult.OK)
{
    Stream myStream;
    myStream = dlg.OpenFile();
    StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
    string columnTitle = "";
    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();
    }
    catch (Exception e)
    {
        MessageBox.Show(e.ToString());
    }
    finally
    {
        sw.Close();
        myStream.Close();
    }
}

方法二:包含图片

Microsoft.Office.Interop.Excel.Application Myexcel = new Microsoft.Office.Interop.Excel.Application();
            if (Myexcel == null)
            {
                return;
            }
            Microsoft.Office.Interop.Excel._Workbook xBk;
            xBk = Myexcel.Application.Workbooks.Add(true);
            Microsoft.Office.Interop.Excel._Worksheet xSt;
            xSt = (Microsoft.Office.Interop.Excel._Worksheet)xBk.ActiveSheet;

            //设置标题等
            string Title = null;
            Title = DateTime.Now.ToLongDateString() + "报价表";
            xSt.Name = Title;
            //报表的格式设置
            //xSt.Cells[1, 6] = Title;
            // xSt.get_Range(Myexcel.Cells[1, 6], Myexcel.Cells[1, 6]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;//设置标题格式为居中对齐
            // xSt.get_Range(Myexcel.Cells[1, 6], Myexcel.Cells[1, 6]).Font.Bold = true;
            //xSt.get_Range(Myexcel.Cells[1, 6], Myexcel.Cells[1, 6]).Font.Size = 20;

            xSt.Cells[1, 1] = "品号";
            xSt.Cells[1, 2] = "品名";
            xSt.Cells[1, 3] = "客户品号";
            xSt.Cells[1, 4] = "图片";
            xSt.Cells[1, 5] = "客户编码";
            xSt.Cells[1, 6] = "客户名称";
            xSt.Cells[1, 7] = "数量";
            xSt.Cells[1, 8] = "币种";
            xSt.Cells[1, 9] = "汇率";
            xSt.Cells[1, 10] = "原币单价";
            xSt.Cells[1, 11] = "原币总价";
            xSt.Cells[1, 12] = "本币单价";
            xSt.Cells[1, 13] = "本币总价";
            xSt.Cells[1, 14] = "创建时间";

            //下面是用循环把datagridview中的内容写到excel
            for (int rowIndex = 0; rowIndex < this.dgvQuotation.Rows.Count; rowIndex++)
            {
                int colIndex = 0;
                for (colIndex = 1; colIndex <= dgvQuotation.ColumnCount; colIndex++)
                {
                    String value = null;
                    if (dgvQuotation.Rows[rowIndex].Cells[colIndex - 1].Value != null)
                    {
                        value = dgvQuotation.Rows[rowIndex].Cells[colIndex - 1].Value.ToString();
                        if (dgvQuotation.Columns[colIndex - 1].Name == "图片") //处理
                        {
                            Image img;
                            //如果是二进制形式:
                            //MemoryStream ms = new MemoryStream((byte[])dgvQuotation.Rows[rowIndex].Cells[colIndex - 1].Value);
                            if (File.Exists(@"D:\产品图片\" + dgvQuotation.Rows[rowIndex].Cells[0].Value.ToString() + ".jpg"))
                            {
                                //需要判断是否存在图片
                                 img = Image.FromFile(@"D:\产品图片\" + dgvQuotation.Rows[rowIndex].Cells[0].Value.ToString() + ".jpg");//双引号里是图片的路径

                            }
                            else
                            {
                                //需要判断是否存在图片
                                 img = Image.FromFile(@"D:\产品图片\LOGO.jpg");//双引号里是图片的路径

                            }

                            //Image img = Image.FromStream(ms);
                            //路径
                           // Image img = GetImage(value);

                            string tmpName = tmpPath + "\\temp" + rowIndex + ".bmp";
                            img.Save(tmpName);
                            string cellAddr = (GetAddress(rowIndex + 4, colIndex));
                            Microsoft.Office.Interop.Excel.Range range = (Microsoft.Office.Interop.Excel.Range)xSt.get_Range(cellAddr, Type.Missing);
                            float left = float.Parse(range.Left.ToString());
                            float top = float.Parse(range.Top.ToString());
                            float width = float.Parse(range.Width.ToString());
                            float height = float.Parse(range.Height.ToString());
                            xSt.Shapes.AddPicture(tmpName, MsoTriState.msoFalse, MsoTriState.msoTrue, left, top, width, height);
                            //xSt.Shapes.AddPicture(tmpName, MsoTriState.msoFalse, MsoTriState.msoTrue, left, top, 200, 200);
                            continue;

                        }

                    }

                    xSt.Cells[rowIndex + 4, colIndex] = value;
                }

            }

            //后台处理
            //用户无法看到
            Myexcel.Visible = false;
            //允许打开对话框保存文件
            Myexcel.DisplayAlerts = true;

           // xBk.Close(true, "D:\\1.xls", null);
            xSt = null;
            xBk = null;
            Myexcel.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(Myexcel);
            Myexcel = null;

[WinForm]dataGridView导出到EXCEL的更多相关文章

  1. winform DataGridView 导出到Excel表格 分类: WinForm 2014-07-04 10:48 177人阅读 评论(0) 收藏

    public bool ExportDataGridview(DataGridView gridView)         {             if (gridView.Rows.Count ...

  2. DataGridView导出到Excel的三个方法

    #region DataGridView数据显示到Excel /// <summary> /// 打开Excel并将DataGridView控件中数据导出到Excel /// </s ...

  3. c# datagridview导出到excel【转载】

    c# datagridview导出到excel[转载] http://hi.baidu.com/weizier/blog/item/8212caea1123b4d6d439c9fe.html 本作者使 ...

  4. C# - VS2019 DataGridView导出到Excel的三种方法

    //原文出处:http://www.yongfa365.com/Item/DataGridViewToExcel.html 1 #region DataGridView数据显示到Excel /// & ...

  5. Winform 中 dataGridView 导出到Excel中的方法总结

    最近,在做CS端数据导出到Excel中时网上找了很多代码感觉都不是自己想要的,通过自己的整理归纳得到一个比较通用的方法,就给大家分享一下: 该方法需要用到两个参数(即对象),一个  DataGridV ...

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

    准备工作就是可以分页的DataGridView,和两个按钮,一个用来导出当前页数据到Excel,一个用来导出全部数据到Excel 没有使用SaveFileDialog,但却可以弹出保存对话框来 先做导 ...

  7. winform datagridview 导出excel

    using System;using System.Collections.Generic;using System.Text;using System.IO;using Microsoft.Offi ...

  8. WinForm中DataGridView导出为Excel(快速版)

    public static void ExportExcel(DataGridView myDGV, string fileName) { string saveFileName = fileName ...

  9. DataGridView 导出到Excel

    #region 导出四个表格到Excel /// <summary> /// 导出四个表格到Excel /// </summary> /// <param name=&q ...

随机推荐

  1. ubuntu查看IO

    在命令行直接 cp 一个比较大的文件时,由于没有提示信息,总感觉很不放心,可以通过查看IO的方式确认cp操作的进展程度. 查看IO可以使用iostat命令,但是前提是要安装sysstat sudo a ...

  2. ABP文档笔记 - 数据过滤

    预定义的过滤 ISoftDelete 软删除过滤用来在查询数据库时,自动过滤(从结果中抽取)已删除的实体.如果一个实体可以被软删除,它必须实现ISoftDelete接口,该接口只定义了一个IsDele ...

  3. TypeScript入门教程

    TypeScript是什么 TypeScript是JavaScript的一个超集 TypeScript需要编译为JavaScript才能运行(语法糖) TypeScript提供了类型系统,规范类似Ja ...

  4. MySQL EXTRACT() 函数

    定义和用法 EXTRACT() 函数用于返回日期/时间的单独部分,比如年.月.日.小时.分钟等等. 语法 EXTRACT(unit FROM date) date 参数是合法的日期表达式.unit 参 ...

  5. Dynamics CRM2016 Web API之删除单个查找字段值

    之前的博文中有介绍过,Web Api中的一个删除单个属性的Api但没提供查找字段的删除方法,本篇补充上,这里给出的示例代码是C#的(主要看url的拼接),看下url中最后的/$ref,这个标示表明了当 ...

  6. Request JSON

    https://developer.android.com/training/volley/request.html Request JSON Volley provides the followin ...

  7. Lua热更新(hotfix)

    Lua热更新(hotfix)(金庆的专栏)hotfixLua 5.2/5.3 hotfix. Hot update functions and keep old data.https://github ...

  8. 剑指Offer——求职必备神器

    剑指Offer--求职必备神器 前言   不管是公司网申.银行招聘.面试等等,"谈谈你的职业规划"."以往工作中遇到了哪些棘手问题?你是如何解决的?".&quo ...

  9. Android自定义处理崩溃异常

    用过安卓手机的用户以及安卓开发者们会时长碰到程序异常退出的情况,普通用户遇到这种情况,肯定非常恼火,甚至会骂一生垃圾软件,然后卸载掉.那么开发者们在开发过程中遇到这种情况给怎么办呢,当然,你不可能世界 ...

  10. 12 SharedPreferences

    SharedPreferences 创建方式 SharedPreferences preferences = getPreferences(Context context ,int mode); 参数 ...