把datagridview的数据输出为Excel,Word的二种应用

2024-03-07 09:08

本文主要是介绍把datagridview的数据输出为Excel,Word的二种应用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

public static void ExportData(DataGridView srcDgv,string fileName)//导出数据,传入一个datagridview和一个文件路径

        {

            string type = fileName.Substring(fileName.IndexOf(".")+1);//获得数据类型

            if (type.Equals("xls",StringComparison.CurrentCultureIgnoreCase))//Excel文档

            {

                Excel.Application excel = new Excel.Application();

                try

                {

                    excel.DisplayAlerts = false;

                    excel.Workbooks.Add(true);

                    excel.Visible = false;

                    for (int i = 0; i < srcDgv.Columns.Count; i++)//设置标题

                    {

                        excel.Cells[2, i+1] = srcDgv.Columns[i].HeaderText;

                    }

                    for (int i = 0; i < srcDgv.Rows.Count; i++)//填充数据

                    {

                        for (int j = 0; j < srcDgv.Columns.Count; j++)

                        {

                            excel.Cells[i + 3, j + 1] = srcDgv[j, i].Value;

                        }

                    }

                    excel.Workbooks[1].SaveCopyAs(fileName);//保存

                }

                finally

                {

                    excel.Quit();

                }

                return;

            }

            //保存Word文件

            if (type.Equals("doc", StringComparison.CurrentCultureIgnoreCase))

            {

                object path = fileName;

                Object none=System.Reflection.Missing.Value;

                Word.Application wordApp = new Word.Application();

                Word.Document document = wordApp.Documents.Add(ref none, ref none, ref none, ref none);

                //建立表格

                Word.Table table= document.Tables.Add(document.Paragraphs.Last.Range, srcDgv.Rows.Count+1, srcDgv.Columns.Count, ref none, ref none);

                try

                {

                    

                    for (int i = 0; i < srcDgv.Columns.Count; i++)//设置标题

                    {

                        table.Cell(1, i + 1).Range.Text = srcDgv.Columns[i].HeaderText;

                    }

                    for (int i = 0; i < srcDgv.Rows.Count; i++)//填充数据

                    {

                        for (int j = 0; j < srcDgv.Columns.Count; j++)

                        {

                            

                            table.Cell(i + 2, j + 1).Range.Text = srcDgv[j, i].Value.ToString();

                        }

                    }

                    document.SaveAs(ref path, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none);

                    document.Close(ref none, ref none, ref none);

                }

                finally

                {

                    wordApp.Quit(ref none, ref none, ref none);

                }

            }

        }

/// <summary>
/// 将DataGrid中的数据导入 Excel中,并显示 Excel应用程序,

/// 注意调用该方法必须有安装 Excel 2000应用程序,并且假定DataGrid中绑定的是一DataSet
/// </summary>
/// <param name="grid"></param>
/// <param name="ReportTitle"></param>
public static void ExportDataGridTo Excel(DataGrid grid,string ReportTitle)
{
DataTable myTable = ((DataSet)grid.DataSource).Tables[0];

try
{
Excel.Application xlApp = new Excel.ApplicationClass();

int rowIndex;
int colIndex;

rowIndex = 2;
colIndex = 0;

Excel.Workbook xlBook =xlApp.Workbooks.Add(true);

if (grid.TableStyles.Count >0 )
{
Excel.Range range = xlApp.get_Range(xlApp.Cells[1,1],xlApp.Cells[1,grid.TableStyles[0].GridColumnStyles.Count]);
range.MergeCells = true;
xlApp.ActiveCell.FormulaR1C1 = ReportTitle;
xlApp.ActiveCell.Font.Size = 18;
xlApp.ActiveCell.Font.Bold = true;

foreach(DataGridColumnStyle colu in grid.TableStyles[0].GridColumnStyles)
{
colIndex=colIndex +1;
xlApp.Cells[2,colIndex] = colu.HeaderText ;
}

//得到的表所有行,赋值给单元格

for (int row = 0;row < myTable.Rows.Count;row++)
{
rowIndex = rowIndex + 1;
colIndex = 0;
for (int col=0;col<grid.TableStyles[0].GridColumnStyles.Count;col++)
{
colIndex = colIndex + 1;
xlApp.Cells[rowIndex, colIndex] = grid[row,col].T ostring();
}
}
}
else
{
Excel.Range range = xlApp.get_Range(xlApp.Cells[1,1],xlApp.Cells[1,myTable.Columns.Count]);
range.MergeCells = true;
xlApp.ActiveCell.FormulaR1C1 = ReportTitle;
xlApp.ActiveCell.Font.Size = 18;
xlApp.ActiveCell.Font.Bold = true;

//将表中的栏位名称填到 Excel的第一行
foreach(DataColumn Col in myTable.Columns)
{
colIndex = colIndex + 1;
xlApp.Cells[2, colIndex] = Col.ColumnName;
}

//得到的表所有行,赋值给单元格

for (int row = 0;row < myTable.Rows.Count;row++)
{
rowIndex = rowIndex + 1;
colIndex = 0;
for (int col=0;col<myTable.Columns.Count;col++)
{
colIndex = colIndex + 1;
xlApp.Cells[rowIndex, colIndex] = grid[row,col].T ostring();
}
}
}

xlApp.get_Range(xlApp.Cells[2, 1], xlApp.Cells[2, colIndex]).Font.Bold = true;
xlApp.get_Range(xlApp.Cells[2, 1], xlApp.Cells[rowIndex, colIndex]).Borders.LineStyle = 1;

xlApp.Cells.EntireColumn.AutoFit();
xlApp.Cells.VerticalAlignment = Excel.Constants.xlCenter ;
xlApp.Cells.HorizontalAlignment = Excel.Constants.xlCenter ;

xlApp.Visible = true;
}
catch(Exception e)
{
throw e;
}
}

 

这篇关于把datagridview的数据输出为Excel,Word的二种应用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/783026

相关文章

CSS中的Static、Relative、Absolute、Fixed、Sticky的应用与详细对比

《CSS中的Static、Relative、Absolute、Fixed、Sticky的应用与详细对比》CSS中的position属性用于控制元素的定位方式,不同的定位方式会影响元素在页面中的布... css 中的 position 属性用于控制元素的定位方式,不同的定位方式会影响元素在页面中的布局和层叠关

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

SQL Server修改数据库名及物理数据文件名操作步骤

《SQLServer修改数据库名及物理数据文件名操作步骤》在SQLServer中重命名数据库是一个常见的操作,但需要确保用户具有足够的权限来执行此操作,:本文主要介绍SQLServer修改数据... 目录一、背景介绍二、操作步骤2.1 设置为单用户模式(断开连接)2.2 修改数据库名称2.3 查找逻辑文件名

canal实现mysql数据同步的详细过程

《canal实现mysql数据同步的详细过程》:本文主要介绍canal实现mysql数据同步的详细过程,本文通过实例图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的... 目录1、canal下载2、mysql同步用户创建和授权3、canal admin安装和启动4、canal

使用SpringBoot整合Sharding Sphere实现数据脱敏的示例

《使用SpringBoot整合ShardingSphere实现数据脱敏的示例》ApacheShardingSphere数据脱敏模块,通过SQL拦截与改写实现敏感信息加密存储,解决手动处理繁琐及系统改... 目录痛点一:痛点二:脱敏配置Quick Start——Spring 显示配置:1.引入依赖2.创建脱敏

C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式

《C#实现将Office文档(Word/Excel/PDF/PPT)转为Markdown格式》Markdown凭借简洁的语法、优良的可读性,以及对版本控制系统的高度兼容性,逐渐成为最受欢迎的文档格式... 目录为什么要将文档转换为 Markdown 格式使用工具将 Word 文档转换为 Markdown(.

详解如何使用Python构建从数据到文档的自动化工作流

《详解如何使用Python构建从数据到文档的自动化工作流》这篇文章将通过真实工作场景拆解,为大家展示如何用Python构建自动化工作流,让工具代替人力完成这些数字苦力活,感兴趣的小伙伴可以跟随小编一起... 目录一、Excel处理:从数据搬运工到智能分析师二、PDF处理:文档工厂的智能生产线三、邮件自动化:

Python实现自动化Word文档样式复制与内容生成

《Python实现自动化Word文档样式复制与内容生成》在办公自动化领域,高效处理Word文档的样式和内容复制是一个常见需求,本文将展示如何利用Python的python-docx库实现... 目录一、为什么需要自动化 Word 文档处理二、核心功能实现:样式与表格的深度复制1. 表格复制(含样式与内容)2

Python数据分析与可视化的全面指南(从数据清洗到图表呈现)

《Python数据分析与可视化的全面指南(从数据清洗到图表呈现)》Python是数据分析与可视化领域中最受欢迎的编程语言之一,凭借其丰富的库和工具,Python能够帮助我们快速处理、分析数据并生成高质... 目录一、数据采集与初步探索二、数据清洗的七种武器1. 缺失值处理策略2. 异常值检测与修正3. 数据

Python使用Tkinter打造一个完整的桌面应用

《Python使用Tkinter打造一个完整的桌面应用》在Python生态中,Tkinter就像一把瑞士军刀,它没有花哨的特效,却能快速搭建出实用的图形界面,作为Python自带的标准库,无需安装即可... 目录一、界面搭建:像搭积木一样组合控件二、菜单系统:给应用装上“控制中枢”三、事件驱动:让界面“活”