简体   繁体   中英

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". "i" is basically the column number (A + i), for Example A2, A3. The Console.WriteLine of the code returns me nothing, so basically is still "". How do I fix this?

Example on 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. 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.

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

I think this is the snippet you need along with the 'GetCellValue' function found at the bottom of the article

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). Give that a try and then let us know any errors you get.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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