• winform datagridview 导出excel


            #region【方法:导出excel事件响应方法】
            private void btnExport_Click(object sender, EventArgs e)
            {
                string a = "D:" + "\DataView.xls";
                ExportExcels(a, dgDataView);
            }
            #endregion
    

      


    #region【导出excel方法】 /// <summary> /// <param name="fileName">文件路径</param> /// <param name="myDGV">控件DataGridView</param> /// </summary> private void ExportExcels(string fileName, DataGridView myDGV) { string saveFileName = ""; SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.DefaultExt = "xls"; saveDialog.Filter = "Excel文件|*.xls"; saveDialog.FileName = fileName; 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; } Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks; Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 //写入标题 for (int i = 0; i < myDGV.ColumnCount; i++) { worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText; } float sumcount = 0; //写入数值 if(myDGV.Rows.Count < numMaxCount.Value) { sumcount = myDGV.Rows.Count; } else { sumcount = (float)numMaxCount.Value; } for (int r = 0; r < sumcount; 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("导出文件时出错,文件可能正被打开! " + ex.Message); } } xlApp.Quit(); GC.Collect();//强行销毁 MessageBox.Show("文件: " + fileName + ".xls 保存成功", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } #endregion #endregion }

      

  • 相关阅读:
    JavaScript实现网页换肤
    JavaScript实现鼠标效果
    JavaScript实现复选框的全选、不选、反选
    处理器解决物联网和人工智能的融合
    用小神经网络和光谱仪优化关键词识别
    电阻存储器为edge-AI提供了仿生架构
    为什么edge AI是一个无需大脑的人
    满足实时人工智能的计算需求
    传感器可以让智能手机测量生命体征
    接触追踪解决方案建立在UWB而不是蓝牙上
  • 原文地址:https://www.cnblogs.com/yanranziruo/p/10429975.html
Copyright © 2020-2023  润新知