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

时间:2016-07-13 23:44:31

标签: c# excel winforms visual-studio-2015

好的,所以我在互联网上阅读了很多文章,但它们不起作用! 我基本上想要当我点击“button1”时,单元格的值将被“复制”并“粘贴”到名为“currentName”的字符串中,然后将创建一个文件夹,其名称是当前值“ currentName”。 对于例A2,A3,“i”基本上是列号(A + i)。 代码的Console.WriteLine没有返回任何内容,所以基本上仍然是“”。 我该如何解决这个问题?

Example on MDSN

整个守则:

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);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

 Directory.CreateDirectory(@"C:\\Users\\talha\\Google Drive\\Clients_excel\\" + currentName);

我看到的一个问题是你使用@ literal但你也有转义反斜杠...但是反斜杠实际上并没有被转义,因为你在字符串前面使用了@ literal符号​​。所以目录路径在每个目录中都会有两个反斜杠,这是行不通的。 fileName字符串很好,因为你没有使用@那里。您必须选择使用转义反斜杠(\) @而不是两者。

我还会使用CreateDirectory方法use a Try Catch,否则如果由于某种原因无法创建目录,您的程序将抛出异​​常,我相信这种情况正在发生。

答案 1 :(得分:0)

您是否尝试过与此处所述相关的内容:

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

我认为这是您需要的代码段以及文章底部的“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);

如果不起作用,则在文件名周围添加一些验证。首先检查excel文件是否存在,检查您引用的单元格中是否有值(您没有返回Null)。尝试一下,然后告诉我们你得到的任何错误。