简体   繁体   English

来自 excel 表的 C# 变量

[英]C# variables from an excel sheet

so i want to get data from certain boxes in an excel file.所以我想从 excel 文件中的某些框中获取数据。 i have written the following code:我写了以下代码:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop.Excel;
using _Excel = Microsoft.Office.Interop.Excel;

namespace Work
{
    class Excel
    {
        string path = "";
        _Application excel = new _Excel.Application();
        Workbook wb;
        Worksheet ws;
        public Excel(string path, int Sheet)
        {
            this.path = path;
            wb = excel.Workbooks.Open(path);
            ws = (_Excel.Worksheet)wb.Worksheets[Sheet];
        }
    }
}

and this is my program:这是我的程序:

using System;

namespace Work
{
    class Program
    {
        static void Main(string[] args)
        {
            string file_name = "C:\\Users\\Aidan\\Desktop\test.xlsx";
            Excel excel = new Excel(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=No'", file_name), 1);
        }
    }
}

for some reason i get this following message:出于某种原因,我收到以下消息:

Unhandled exception.未处理的异常。 System.IO.FileNotFoundException: Could not load file or assembly 'Interop.Microsoft.Office.Interop.Excel, Version=1.9.0.0, Culture=neutral, PublicKeyToken=null'. System.IO.FileNotFoundException:无法加载文件或程序集“Interop.Microsoft.Office.Interop.Excel,版本=1.9.0.0,文化=中性,PublicKeyToken=null”。 The system cannot find the file specified.该系统找不到指定的文件。 File name: 'Interop.Microsoft.Office.Interop.Excel, Version=1.9.0.0, Culture=neutral, PublicKeyToken=null'文件名:'Interop.Microsoft.Office.Interop.Excel,版本=1.9.0.0,文化=中性,PublicKeyToken=null'

does someone know what is there to do?有人知道有什么办法吗? i appreciate any help!我很感激任何帮助!

EDIT: so ive found a new way to write the code online and it still gives me the same error but a bit diffrent:编辑:所以我找到了一种在线编写代码的新方法,它仍然给我同样的错误,但有点不同:

Unhandled exception.未处理的异常。 System.IO.FileNotFoundException: Could not load file or assembly 'office, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'. System.IO.FileNotFoundException:无法加载文件或程序集“办公室,版本=15.0.0.0,文化=中性,PublicKeyToken=71e9bce111e9429c”。 The system cannot find the file specified.该系统找不到指定的文件。 File name: 'office, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'文件名:'office,版本=15.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c'

this is the new code (replaces the class Excel):这是新代码(替换 class Excel):

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
namespace Work
{
    class Program
    {
        const int n = 30;
        static void getExcelFile()
        {

            //Create COM Objects. Create a COM object for everything that is referenced
            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\Users\Orna\Desktop\test.xlsx");
            Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
            Excel.Range xlRange = xlWorksheet.UsedRange;

            //iterate over the rows and columns and print to the console as it appears in the file
            //excel is not zero based!!
            for (int i = 1; i <= n; i++)
            {
                d[i - 1] = new Date(xlRange.Cells[i, 1].ToString(), xlRange.Cells[i, 2].ToString(), (int)xlRange.Cells[i, 23], (int)xlRange.Cells[i, 4], (int)xlRange.Cells[i, 5], (int)xlRange.Cells[i, 6], (int)xlRange.Cells[i, 7], (int)xlRange.Cells[i, 8], (int)xlRange.Cells[i, 9], (int)xlRange.Cells[i, 10], (int)xlRange.Cells[i, 11] , (int)xlRange.Cells[i, 12], (int)xlRange.Cells[i, 13], (int)xlRange.Cells[i, 14]);
            }

            //cleanup
            GC.Collect();
            GC.WaitForPendingFinalizers();

            //rule of thumb for releasing com objects:
            //  never use two dots, all COM objects must be referenced and released individually
            //  ex: [somthing].[something].[something] is bad

            //release com objects to fully kill excel process from running in the background
            Marshal.ReleaseComObject(xlRange);
            Marshal.ReleaseComObject(xlWorksheet);

            //close and release
            xlWorkbook.Close();
            Marshal.ReleaseComObject(xlWorkbook);

            //quit and release
            xlApp.Quit();
            Marshal.ReleaseComObject(xlApp);
        }

btw dont mind the date class, thats something else and the problem doesnt come from that.顺便说一句,不介意日期 class,那是别的东西,问题不来自于此。 id still very much appreciate the help.我仍然非常感谢您的帮助。 thanks.谢谢。

For the simplest, fastest way to read from Excel in C# I wouldn't recommend the overhead of Interop it's too clunky and cumbersome.对于从 C# 中的 Excel 读取的最简单、最快的方法,我不建议使用 Interop 的开销,它太笨重和麻烦。

There is a great little library that's super easy and fast to use called LightWeightExcelReader.有一个很棒的小库,使用起来超级简单快捷,叫做 LightWeightExcelReader。 https://github.com/ChrisHodges/LightweightExcelReader . https://github.com/ChrisHodges/LightweightExcelReader Check the readme file for a simple example of doing exactly what you want.检查自述文件以获取完全按照您的意愿进行操作的简单示例。

If you need to write as well as read Excel files, I'd recommend https://github.com/ClosedXML/ClosedXML instead如果您需要编写和阅读 Excel 文件,我建议您改为 https://github.com/ClosedXML/ClosedXML

According to your description, you want to query data from excel sheet.根据您的描述,您想从 excel 表中查询数据。

You can try the following code to solve this problem.您可以尝试以下代码来解决此问题。

Please install nuget package->LightWeightExcelReader firstly.请先安装 nuget package->LightWeightExcelReader。

using LightWeightExcelReader;
using System;
using System.Collections.Generic;
namespace _4._4Excel
{
    class Program
    {
        static void Main(string[] args)
        {
            Excel.getExcelFile();
        }
    }
    class Excel
    {
        public static void getExcelFile()
        {

            //Instatiate a spreadsheet reader by file path:
            var excelReader = new ExcelReader(@"\...\test1.xlsx");         
            //Get a worksheet by index:
            var sheetReader = excelReader[0];
            var dictionaryOfCellValues = new Dictionary<string, object>();
            //Use ReadNext() to read the next cell in the spreadsheet:
            while (sheetReader.ReadNext())
            {
                dictionaryOfCellValues.Add(sheetReader.Address, sheetReader.Value);
            }
            IEnumerable<object> cellsFromA1ToD4 = sheetReader["A1", "C4"];
            foreach (object obj in cellsFromA1ToD4)
            Console.WriteLine(obj);
            Console.ReadKey();         
        }
    }
}

Excel: Excel:

在此处输入图像描述

Result:结果:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM