前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >DataGridView输出或保存为Excel文件(支持超过65536行多Sheet输出)

DataGridView输出或保存为Excel文件(支持超过65536行多Sheet输出)

作者头像
跟着阿笨一起玩NET
发布2018-09-18 13:40:59
1.4K0
发布2018-09-18 13:40:59
举报
代码语言:javascript
复制
/// <summary>
        /// DataGridView控件数据导出到Excel,可设定每一个Sheet的行数
        /// 建立多个工作表来装载更多的数据
        /// </summary>
        /// <param name="ExportGrid">DataGridView控件</param>
        /// <param name="fullFileName">保存的文件路径</param>
        /// <param name="SheetRowsCount">每一个Sheet的行数</param>
        /// <param name="IsOpenFile">是否打开文件</param>
        /// <returns>True/False</returns>
        public bool OutputFileToExcel(DataGridView ExportGrid, string fullFileName, int SheetRowsCount, bool IsOpenFile)
        {
            int id = 0;
            bool ExportSuccess = false;
            //如果网格尚未数据绑定
            if (ExportGrid == null)
            {
                return false;
            }
            ////Excel2003 工作表大小 65,536 行乘以 256 列 
            //if (ExportGrid.Rows.Count > 65536 || ExportGrid.ColumnCount > 256)
            //{
            //    return false;
            //}
            // 列索引,行索引
            int colIndex = 0;
            int rowIndex = 0;
            int objcetRowIndex = 0;
            //总可见列数,总可见行数
            int colCount = ExportGrid.Columns.GetColumnCount(DataGridViewElementStates.Visible);
            int rowCount = ExportGrid.Rows.GetRowCount(DataGridViewElementStates.Visible);
            if (rowCount == 0 || colCount == 0)  //如果DataGridView中没有行,返回
            {
                return false;
            }
            // 创建Excel对象                    
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                return false;
            }
            // 创建Excel工作薄
            Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
            Microsoft.Office.Interop.Excel.Range range = null;
            IntPtr t = new IntPtr(xlApp.Hwnd);
 
            object oMissing = System.Reflection.Missing.Value;
            int JLevel = 0;
            JLevel = int.Parse(Math.Ceiling((ExportGrid.RowCount + 0.00) / SheetRowsCount).ToString());
            xlBook.Worksheets.Add(oMissing, oMissing, JLevel - 1, oMissing);
            for (int i = 1; i < xlBook.Worksheets.Count + 1; i++)
            {
                ((Microsoft.Office.Interop.Excel.Worksheet)xlBook.Worksheets[i]).Name = "数据表" + i.ToString();
            }
            for (int j = 1; j < JLevel + 1; j++)
            {
                colIndex = 0;
                objcetRowIndex = 0;
                Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Worksheets.get_Item("数据表" + j.ToString());
                // 创建缓存数据
                object[,] objData = new object[SheetRowsCount + 1, colCount];
                // 获取列标题,隐藏的列不处理
                for (int i = 0; i < ExportGrid.ColumnCount; i++)
                {
                    if (ExportGrid.Columns[i].Visible)
                    {
                        objData[objcetRowIndex, colIndex++] = ExportGrid.Columns[i].HeaderText;
                        if (ExportGrid.Columns[i].ValueType.ToString() == "System.String")
                        {
                            //设置成文本型,有效避免将前置的0自动删除了
                            range = xlSheet.get_Range(xlSheet.Cells[1, colIndex], xlSheet.Cells[SheetRowsCount + 1, colIndex]);
                            range.NumberFormat = "@";
                        }
                    }
                }
 
                for (int i = (j - 1) * SheetRowsCount; i < SheetRowsCount * j; i++)
                {
                    rowIndex++;
                    objcetRowIndex++;
                    colIndex = 0;
                    for (int k = 0; k < ExportGrid.ColumnCount; k++)
                    {
                        if (ExportGrid.Columns[k].Visible)
                        {
                            objData[objcetRowIndex, colIndex++] = ExportGrid[k, rowIndex - 1].Value;
                        }
                    }
                    Application.DoEvents();
 
 
                    if (i >= ExportGrid.RowCount - 1)
                    {
                        break;
                    }
 
                }
                // 写入Excel
                range = xlSheet.get_Range(xlSheet.Cells[1, 1], xlSheet.Cells[SheetRowsCount + 1, colCount]);
                range.Value2 = objData;
                //设置列头格式
                range = xlSheet.get_Range(xlSheet.Cells[1, 1], xlSheet.Cells[1, colCount]);
                range.Font.Bold = true;
                range.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
 
                //设置报表表格为最适应宽度
                xlSheet.Cells.EntireColumn.AutoFit();
                xlSheet.Cells.VerticalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
                xlSheet.Cells.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlLeft;
                xlSheet.UsedRange.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
            }
 
            // 保存
            try
            {
                xlBook.Saved = true;
                xlBook.SaveCopyAs(fullFileName);
                ExportSuccess = true;
            }
            catch
            {
                ExportSuccess = false;
            }
            finally
            {
                //释放资源,关闭进程
                xlApp.Quit();
                GetWindowThreadProcessId(t, out id);
                System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(id);
                p.Kill();
            }
            if (IsOpenFile == true)
            {
                HS.Audit.Utilite.FileOperate FO = new HS.Audit.Utilite.FileOperate();
                FO.OpenFile(fullFileName);
            }
            return ExportSuccess;
        }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2012-04-14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
腾讯云 BI
腾讯云 BI(Business Intelligence,BI)提供从数据源接入、数据建模到数据可视化分析全流程的BI能力,帮助经营者快速获取决策数据依据。系统采用敏捷自助式设计,使用者仅需通过简单拖拽即可完成原本复杂的报表开发过程,并支持报表的分享、推送等企业协作场景。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档