在DataGridView中显示ms excel数据 [英] Displaying ms excel data in DataGridView
本文介绍了在DataGridView中显示ms excel数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
HI
我想在DataGridView中的Excel电子表格上显示数据,请使用C#。
HI
I want to display data on an excel spreadsheet in DataGridView please am using C#.
推荐答案
参见如何从Excel工作表中获取数据的一些建议到c#中的datagridview [ ^ ]
我在项目中使用了很长时间,也许会有所帮助:
I used this a long time back in my project, maybe it will help:
public ArrayList ProcessWorkbook(string filePath)
{
string file = filePath;
Excel.Application excel = null;
Excel.Workbook wkb = null;
ArrayList al = new ArrayList();
try
{
excel = new Excel.Application();
wkb = ExcelTools.OpenBook(excel, file, false, true, false);
Excel.Worksheet sheet = wkb.Sheets["Adresses"] as Excel.Worksheet;
Excel.Range range = null;
if (sheet != null)
range = sheet.get_Range("A1:X6702", Missing.Value);
if (range != null)
{
foreach (Excel.Range r in range)
{
al.Add(r.Text);
}
}
}
catch (Exception ex)
{
//if you need to handle stuff
Console.WriteLine(ex.Message);
}
finally
{
if (wkb != null)
ExcelTools.ReleaseRCM(wkb);
if (excel != null)
ExcelTools.ReleaseRCM(excel);
}
return al;
}
//----------------
public static class ExcelTools
{
public static Excel.Workbook OpenBook(Excel.Application excelInstance, string fileName, bool readOnly, bool editable,
bool updateLinks)
{
Excel.Workbook book = excelInstance.Workbooks.Open(
fileName, updateLinks, readOnly,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, editable, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
return book;
}
public static void ReleaseRCM(object o)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
}
catch
{
}
finally
{
o = null;
}
}
}
这篇关于在DataGridView中显示ms excel数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文