如何用c#中的dataGridView1查询excel表格中的数据并显示?,(excel表格已经导入form中)

2024-11-25 21:34:42
推荐回答(1个)
回答1:

实话实说,找来的 = =using System;using System.Collections.Generic;using System.Text;using System.IO;using System.Data;using System.Windows.Forms;using Microsoft.Office.Interop.Excel;namespace Property_managementset }public static System.Windows.Forms.ProgressBar _toolStripProgressBar1set }public static Timer _timeset }public static DataSet _objSetset }public static void ExportTOExcel2()elseMicrosoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks;Microsoft.Office.Interop.Excel.Workbook book = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss));Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet;sheet.Name = "test";//生成字段名称for (int i = 0; i < gridView.ColumnCount; i++)//填充数据for (int i = 0; i < gridView.RowCount; i++)else}toolStripProgressBar1.Value += 100 / gridView.RowCount;}sheet.SaveAs(strName, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss);book.Close(false, miss, miss);books.Close();excel.Quit();System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);System.Runtime.InteropServices.Marshal.ReleaseComObject(book);System.Runtime.InteropServices.Marshal.ReleaseComObject(books);System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);GC.Collect();MessageBox.Show("数据已经成功导出!!");toolStripProgressBar1.Value = 0;toolStripProgressBar1.Visible = false;System.Diagnostics.Process.Start(strName); }}}}}我把功能放在这个类里了需要添加一个引用右边的资源管理器右键单击“引用”,选择添加引用-》com,找到microsoft excel 11 那个,添加进去如果有个黄色的叹号,建议重装一次office下面是如何使用Export._gridView = GV;//这是指定DatagridViewExport._toolStripProgressBar1 = PB;//如果有滚动条的话加上,没有不设定也行Export._objSet = this.propertyDataSet5.Fee_already.DataSet;//指定你的DatagridView使用的datasetExport.ExportTOExcel2();//调用函数导出