将 DataGridView 导出到 Excel 的简单方法

2024-04-09

我正在尝试将 DataGridView 数据复制到 Excel,并且使用以下代码:

public static void ExportToExcel(DataGridView dgView)
{
    Microsoft.Office.Interop.Excel.Application excelApp = null;

    try
    {
        // instantiating the excel application class
        object misValue = System.Reflection.Missing.Value;
        excelApp = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel.Workbook currentWorkbook = excelApp.Workbooks.Add(Type.Missing);
        Microsoft.Office.Interop.Excel.Worksheet currentWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)currentWorkbook.ActiveSheet;

        currentWorksheet.Columns.ColumnWidth = 18;

        if (dgView.Rows.Count > 0)
        {
            currentWorksheet.Cells[1, 1] = DateTime.Now.ToString("s");
            int i = 1;

            foreach (DataGridViewColumn dgviewColumn in dgView.Columns)
            {
                // Excel work sheet indexing starts with 1
                currentWorksheet.Cells[2, i] = dgviewColumn.Name;
                ++i;
            }

            Microsoft.Office.Interop.Excel.Range headerColumnRange = currentWorksheet.get_Range("A2", "G2");
            headerColumnRange.Font.Bold = true;
            headerColumnRange.Font.Color = 0xFF0000;

            //headerColumnRange.EntireColumn.AutoFit();
            int rowIndex = 0;

            for (rowIndex = 0; rowIndex < dgView.Rows.Count; rowIndex++)
            {
                DataGridViewRow dgRow = dgView.Rows[rowIndex];

                for (int cellIndex = 0; cellIndex < dgRow.Cells.Count; cellIndex++)
                {
                    currentWorksheet.Cells[rowIndex + 3, cellIndex + 1] = dgRow.Cells[cellIndex].Value;
                }
            }

            Microsoft.Office.Interop.Excel.Range fullTextRange = currentWorksheet.get_Range("A1", "G" + (rowIndex + 1).ToString());
            fullTextRange.WrapText = true;
            fullTextRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
        }
        else
        {
            string timeStamp = DateTime.Now.ToString("s");
            timeStamp = timeStamp.Replace(':', '-');
            timeStamp = timeStamp.Replace("T", "__");
            currentWorksheet.Cells[1, 1] = timeStamp;
            currentWorksheet.Cells[1, 2] = "No error occured";
        }

        using (SaveFileDialog exportSaveFileDialog = new SaveFileDialog())
        {
            exportSaveFileDialog.Title = "Select Excel File";
            exportSaveFileDialog.Filter = "Microsoft Office Excel Workbook(*.xlsx)|*.xlsx";

            if (DialogResult.OK == exportSaveFileDialog.ShowDialog())
            {
                string fullFileName = exportSaveFileDialog.FileName;
                // currentWorkbook.SaveCopyAs(fullFileName);
                // indicating that we already saved the workbook, otherwise call to Quit() will pop up
                // the save file dialogue box

                currentWorkbook.SaveAs(fullFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, System.Reflection.Missing.Value, misValue, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, misValue, misValue, misValue);
                currentWorkbook.Saved = true;
                MessageBox.Show("Exported successfully", "Exported to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    finally
    {
        if (excelApp != null)
        {
            excelApp.Quit();
        }
    }
}

但由于记录数量超过20万条,导出时间较长。有没有更快的方法来做到这一点?


试试这个代码。它比普通的互操作方法更快,而且它可以转换为 CSV,可以通过 Excel 轻松读取。

int cols;
//open file 
StreamWriter wr = new StreamWriter("GB STOCK.csv");

//determine the number of columns and write columns to file 
cols = dgvStock.Columns.Count;
for (int i = 0; i < cols - 1; i++)
{ 
    wr.Write(dgvStock.Columns[i].Name.ToString().ToUpper() + ",");
} 
wr.WriteLine();

//write rows to excel file
for (int i = 0; i < (dgvStock.Rows.Count - 1); i++)
{ 
    for (int j = 0; j < cols; j++)
    { 
        if (dgvStock.Rows[i].Cells[j].Value != null)
        {
            wr.Write(dgvStock.Rows[i].Cells[j].Value + ",");
        }
        else 
        {
            wr.Write(",");
        }
    }

    wr.WriteLine();
}

//close file
wr.Close();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 DataGridView 导出到 Excel 的简单方法 的相关文章

随机推荐

  • 将cpp文件添加到cocos2d-x项目android项目中

    我已按照本教程进行操作http www raywenderlich com 33750 cocos2d x tutorial for ios and android getting started http www raywenderlic
  • Facebook Graph API:如何获取评论中的“来自”字段

    我有一个尚未发布的 Facebook 应用程序 测试模式 我使用页面访问令牌从我自己页面上特定帖子的评论中提取 来自 字段 但它返回空字段 这是我的图形 API 查询 gt post id comments fields from 当我使用
  • 给单元格着色 Google Chart - 散点图

    我在我的一个项目中使用谷歌图表 我需要使用以下代码为谷歌散点图中的一组单元格着色 我在用google visualization arrayToDataTable用于处理数据 以下是我的代码 div div
  • 在 Android 中使用 Service 作为单例

    创建一个不好的做法吗 Service作为单身人士工作 我的意思是一个Service它永远不会停止 并且包含一些其他引擎和Activities会使用 所以Service可能有类似的东西 public class CustomService e
  • 对空间数据使用简单的 for 循环

    抱歉 这将是一个 for 循环 101 问题 我正在努力编写一个简单的 for 循环来根据经度纬度数据生成城市之间的距离表 locations lt read csv distances csv Locations 返回下表 City Ty
  • 具有自由 CORS 政策的公开托管图像? [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我正在做一些将图像加载到画布上的测试 并且正在使用私下里在我们的 aws cdn 上托管图像 这个 c
  • 如何找到 ROI 并检测内部标记?

    我是计算机视觉的初学者 我有一个关于检测和跟踪的问题 我想检测下图中的白色矩形 以确定感兴趣的区域并检测红色标记的轮廓 但我不想利用颜色信息来检测标记 谁能给我关于如何做到这一点的建议 如果您只想检测圆圈 则可以使用经过调整的霍夫变换 ht
  • 具有有序索引的 R 向量-向量匹配

    这里我有两个字符串向量 它们的顺序很重要并且无法更改 vec1 lt c carrot carrot carrot apple apple mango mango cherry cherry vec2 lt c cherry apple 我
  • 可通过属性名称或索引选项访问的结构

    我对 Python 非常陌生 并试图弄清楚如何创建一个具有可通过属性名称或索引访问的值的对象 例如 os stat 返回 stat result 或 pwd getpwnam 返回 struct passwd 的方式 在试图弄清楚这一点时
  • alloca可以完全替代吗?

    我读过很多地方alloca已过时 不应使用 而应使用可变长度数组 我的问题是这样的 是alloca完全可以用变长数组代替 在我的特定实例中 我有一些看起来像这样的东西 typedef struct int value size t size
  • 如何在 Kotlin 中编写以下代码来实现回调

    我如何像java一样用Kotlin编写 Callback callback new Callback Override public void getCallback ServerResponse serverResponse var ca
  • 基于 RCP 的应用程序的 P2 更新失败

    我尝试通过 P2 更新站点更新基于 Eclipse RCP 3 5 的应用程序 该应用程序包含两个功能 产品是由Eclipse Buckminster P2 更新站点的创建是产品构建的一部分 当通过菜单开始更新时 Update gt Che
  • 为什么这个未使用的 self.hash 方法会导致“无法将字符串转换为整数”错误?

    我正在跑过Lynda Rails 3 教程 http www lynda com Ruby on Rails 3 tutorials essential training 55960 2 html 在某一时刻 在名为 access cont
  • 如何检测重复数据?

    我有一个简单的联系人数据库 但用户输入重复数据时遇到问题 我已经实现了一个简单的数据比较 但不幸的是 输入的重复数据并不完全相同 例如 姓名拼写错误 或者一个人输入 Bill Smith 另一个人输入 William Smith 表示同一个
  • 使用 $(function 等启动 javascript 代码

    我正在研究 Backbone 和来自的待办事项示例应用程序http todomvc com http todomvc com 我注意到有 3 种方法可以在文件中启动代码 function code here function code he
  • Swift 3 LPCM 录音机 |错误:kAudioFileInvalidPacketOffsetError

    下面的录音机仅在第一次时有效 如果您尝试第二次录音 则在尝试 AudioFileWritePackets 时会出现错误 kAudioFileInvalidPacketOffsetError 知道为什么会发生这种情况吗 先感谢您 存储库位于此
  • Spring & JPA:按需创建数据库模式和表

    JPA Spring 是否有可能在运行时创建 删除具有自定义名称和相应表 由 Entity 注释给出 的数据库模式 例如当用户按下按钮时 我只知道关于javax persistence schema generation属性 它们在我的应用
  • 带圆角和锯齿状弧形边框的正方形

    我想知道是否可以用纯 CSS 制作一个带有圆角和缩进边框的正方形 目前我有这个 custom square position relative display block width 75px height 75px border 2px
  • goimports 需要忽略供应商包

    我正在尝试实施dep在我的项目中 这一切都运行良好 但它还添加了一个供应商目录 我现在需要更新我的工具以忽略此目录 否则我提供的软件包将被修改 或者我会收到警告误报 我目前正在使用以下工具 goimports w go vet go lin
  • 将 DataGridView 导出到 Excel 的简单方法

    我正在尝试将 DataGridView 数据复制到 Excel 并且使用以下代码 public static void ExportToExcel DataGridView dgView Microsoft Office Interop E