2016-07-13 19 views
0

私はインターネット上で多くの記事を読んだことがありますが、うまくいきません。 私は基本的に "button1"をクリックすると、セルの値が "currentName"という文字列に "コピー"され、 "貼り付け"られ、その名前が現在の値である間にフォルダが作成されます。 "currentName"。 例A2、A3の場合、「i」は基本的に列番号(A + i)です。 コードのConsole.WriteLineは何も返さないので、基本的にはまだ ""です。 これを修正するにはどうすればよいですか?既存のExcelファイルのセルから値を取得するにはどうすればよいですか? C#

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

私はあなたの編集をロールバックしました。あなたのタイトルに[解決済み]を追加するか、あなたの質問に答えを編集するのはここでは適切ではありません。ここの誰かから得た回答が問題を解決した場合は、[その回答を受け入れる](http://stackoverflow.com/help/someone-answers)でそのことを示すことができます。解決策を見つけて共有したい場合は、下の答えをスペースに記入してください。ここでは、[あなた自身の質問に答える](http://stackoverflow.com/help/self-answer)は完全に受け入れられます。 –

答えて

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を返さない)。それを試してみて、あなたが得るエラーを教えてください。

+0

GetCellValueはボディが必要なので、私はその記事に従うとエラーになるので、{}を追加しなければならないときは、何かを返す必要があります。 {}の中にすべてのコードを置くと、うまくいきません。私はすべてを試しました –

+0

ところで私はこれを置くのですか?値を取得するにはボタンが必要ですが、ボタンをクリックして空にする方法は? –

+0

あなたのコードを掲載していれば(上記の例を含む)、あなたが得ているエラーをお知らせください。 – JohnStack

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

一つの問題は、あなたがリテラル@を使用しますが、あなたはまた、バックスラッシュをエスケープしている...しかし、バックスラッシュが実際にエスケープされていないということです文字列の前に@記号を使用しているからです。そのため、ディレクトリパスには文字通り各ディレクトリに2つのバックスラッシュが付きますが、これはうまくいきません。あなたが@を使わなかったので、fileName文字列はうまくいきます。エスケープされたバックスラッシュ(\)または @を使用するか、両方を使用するかを選択する必要があります。

また、CreateDirectoryメソッドを使用してuse a Try Catchとすると、何らかの理由でディレクトリが作成できない場合、プログラムが例外をスローします。これは確実に起こります。

+0

現在、私はExcelファイルから値を取得したいだけです。 –

+0

既存のExcelファイル内の特定のセルから値を返すにはどうすればよいですか? –