简体   繁体   English

如何从现有Excel文件的单元格中获取值? C#

[英]How to get values from cells of an existing excel file? C#

Okay so I've read a lot of articles on the internet but they don't work!!! 好的,所以我在互联网上阅读了很多文章,但是它们不起作用!!! I basically want that when I click on "button1", the value of a cell will be "copied" and "pasted" into the string called:"currentName", then a folder will be created while its name is the current value of "currentName". 我基本上希望当我单击“ button1”时,将单元格的值“复制”并“粘贴”到名为“ currentName”的字符串中,然后创建一个文件夹,同时其名称为“”的当前值。 currentName”。 "i" is basically the column number (A + i), for Example A2, A3. “ i”基本上是列号(A + i),例如A2,A3。 The Console.WriteLine of the code returns me nothing, so basically is still "". 代码的Console.WriteLine没有返回任何内容,因此基本上还是“”。 How do I fix this? 我该如何解决?

Example on MDSN MDSN上的示例

The whole Code: 整个代码:

using System.IO;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;


namespace For_work
{
public partial class Form1 : Form
{
    public static string currentName;
    public static string GetCellValue(string fileName,
    string sheetName,
    string addressName)
    {
        string value = null;
        fileName = "F:\\Visual Studio\\For_work\\For_work\\files\\excel_file.xlsx";
        // Open the spreadsheet document for read-only access.
        using (SpreadsheetDocument document =
            SpreadsheetDocument.Open(fileName, false))
        {
            // Retrieve a reference to the workbook part.
            WorkbookPart wbPart = document.WorkbookPart;

            // Find the sheet with the supplied name, and then use that 
            // Sheet object to retrieve a reference to the first worksheet.
            Sheet theSheet = wbPart.Workbook.Descendants<Sheet>().
              Where(s => s.Name == sheetName).FirstOrDefault();

            // Throw an exception if there is no sheet.
            if (theSheet == null)
            {
                throw new ArgumentException("Sheet1");
            }

            // Retrieve a reference to the worksheet part.
            WorksheetPart wsPart =
                (WorksheetPart)(wbPart.GetPartById(theSheet.Id));

            // Use its Worksheet property to get a reference to the cell 
            // whose address matches the address you supplied.
            Cell theCell = wsPart.Worksheet.Descendants<Cell>().
              Where(c => c.CellReference == addressName).FirstOrDefault();

            // If the cell does not exist, return an empty string.
            if (theCell != null)
            {
                value = theCell.InnerText;

                // If the cell represents an integer number, you are done. 
                // For dates, this code returns the serialized value that 
                // represents the date. The code handles strings and 
                // Booleans individually. For shared strings, the code 
                // looks up the corresponding value in the shared string 
                // table. For Booleans, the code converts the value into 
                // the words TRUE or FALSE.
                if (theCell.DataType != null)
                {
                    switch (theCell.DataType.Value)
                    {
                        case CellValues.SharedString:

                            // For shared strings, look up the value in the
                            // shared strings table.
                            var stringTable =
                                wbPart.GetPartsOfType<SharedStringTablePart>()
                                .FirstOrDefault();

                            // If the shared string table is missing, something 
                            // is wrong. Return the index that is in
                            // the cell. Otherwise, look up the correct text in 
                            // the table.
                            if (stringTable != null)
                            {
                                value =
                                    stringTable.SharedStringTable
                                    .ElementAt(int.Parse(value)).InnerText;
                            }
                            break;

                        case CellValues.Boolean:
                            switch (value)
                            {
                                case "0":
                                    value = "FALSE";
                                    break;
                                default:
                                    value = "TRUE";
                                    break;
                            }
                            break;
                    }
                }
            }
        }
        value = GetCellValue(fileName, "Sheet1", "A1");
        Console.WriteLine(value);
        // Retrieve the date value in cell A2.
        value = GetCellValue(fileName, "Sheet1", "A2");
        Console.WriteLine(DateTime.FromOADate(double.Parse(value)).ToShortDateString());
        currentName = value;
        return value;
    }
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        Console.WriteLine(currentName);
        for (int i = 2; i < 2064; i++)
        {
            try
            {
                Directory.CreateDirectory(@"D:\FOR WORK" + currentName);
            }
            catch
            {
                Console.Write("Could not create:" + currentName);
            }
        }
    }
}
 Directory.CreateDirectory(@"C:\\Users\\talha\\Google Drive\\Clients_excel\\" + currentName);

One issue I see is that you use the @ literal but you also have escaped backslashes... But the backslashes are not actually escaped since you use the @ literal sign in front of the string. 我看到的一个问题是您使用@文字,但是您也转义了反斜线...但是,由于在字符串前面使用@文字符号,反斜杠实际上并未转义。 So the directory path is literally going to have two backslashes in it at each directory, which won't work. 因此,目录路径实际上将在每个目录中包含两个反斜杠,这将不起作用。 The fileName string is fine though because you did not use the @ there. 尽管fileName字符串很好,因为您在那里没有使用@。 You have to pick to either use escaped backslashes (\\) OR the @ but not both. 您必须选择使用转义的反斜杠(\\) @,但不能同时使用两者。

I would also use a Try Catch with the CreateDirectory method or else your program will throw an exception if for some reason the directory can't be created, which I am sure is happening. 我还将使用带有CreateDirectory方法的Try Catch ,否则如果由于某种原因无法创建目录(您确定正在发生这种情况),您的程序将引发异常。

Have you tried something along the lines of what is explained here: 您是否尝试过按照以下说明进行的尝试:

https://msdn.microsoft.com/en-us/library/office/hh298534.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1 https://msdn.microsoft.com/zh-cn/library/office/hh298534.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1

I think this is the snippet you need along with the 'GetCellValue' function found at the bottom of the article 我认为这是您所需的代码片段,以及本文底部的“ GetCellValue”功能

const string fileName = 
@"C:\users\public\documents\RetrieveCellValue.xlsx";

// Retrieve the value in cell A1.
string value = GetCellValue(fileName, "Sheet1", "A1");
Console.WriteLine(value);

If that isn't working then add some validation around the file name. 如果这不起作用,请在文件名周围添加一些验证。 Check the excel file exists first, check the cell you are referencing has a value in it (you aren't returning Null). 首先检查excel文件是否存在,检查所引用的单元格中是否有值(您不返回Null)。 Give that a try and then let us know any errors you get. 试试看,然后让我们知道您遇到的任何错误。

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

相关问题 如何使用 C# 写入现有 Excel (xlsc) 文件中的特定单元格 - How to write to specific cells in an existing Excel (xlsc) file with C# 如何使用带有 Interop.Excel 库的 C# 从现有 Excel 文件中获取特定元素? - How to get specific elements from an existing Excel file using C# with the Interop.Excel library? 如何将特定的 excel 单元格值导入 C# 中的现有 datagridview 单元格 - How do I import specific excel cell values to existing datagridview cells in C# 如何将数据从C#传递到excel现有文件 - How to pass data from C# to an excel existing file 如何从选定的单元格DataGridView C#获取值? - How to get values from selected cells DataGridView C#? 无法使用 C# 中特定单元格的值更新现有 excel 文件 - Unable to update an existing excel file with values for a certain cell in C# C#Excel Interop:如何格式化单元格以将值存储为文本 - C# Excel Interop: How to format cells to store values as text 如何使用Windows Service C#将值插入Excel单元格 - How to insert values to excel cells using a Windows Service C# 如何从Excel C#获取带有单元格地址的列值 - How to get Column Values with cell Address From Excel c# 在C#中解析Excel文件,单元格似乎被切断为255个字符...我该如何阻止它? - Parsing an Excel file in C#, the cells seem to get cut off at 255 characters… how do I stop that?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM