1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication1
{
class Class1
{
static void Main(string[] args)
{
// Display the number of command line arguments:
object[,] mpart = ReadFile("test.xlsb", "mPart");
object[,] units = ReadFile("test2.xlsb", "units");
}
private static object missing = System.Reflection.Missing.Value;
public static object[,] ReadFile(string filepath, string sheetname)
{
Application xlApp = null;
Workbooks wks = null;
Workbook wb = null;
Sheets sheets = null;
Worksheet sh = null;
object[,] values = null;
try
{
xlApp = new Application();
wks = xlApp.Workbooks;
wb = wks.Open(filepath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
sheets = wb.Worksheets;
sh = (Worksheet)sheets.get_Item(sheetname);
}
catch (Exception ex)
{
throw new Exception(string.Format("Sheet \"{0}\" does not exist in the Excel file", sheetname));
}
finally
{
if (wb != null)
wb.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
if (wks != null)
wks.Close();
if (xlApp != null)
xlApp.Quit();
if (sheets != null)
Marshal.ReleaseComObject(sheets);
if (sh != null)
Marshal.ReleaseComObject(sh);
if (wks != null)
Marshal.ReleaseComObject(wks);
if (wb != null)
Marshal.ReleaseComObject(wb);
if (xlApp != null)
Marshal.ReleaseComObject(xlApp);
sh = null;
sheets = null;
wks = null;
wb = null;
xlApp = null;
GC.GetTotalMemory(false);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.GetTotalMemory(true);
}
return values;
}
}
} |
Partager