2017-09-12 16 views
0

필자는 Excel 시트의 B 열에 "양호한"셀 범위를 얻었습니다. "D"열에서 해당 셀을 찾고 해당 셀 범위를 만듭니다. 모든 셀을 하나의 문자열로 변환하여 메모장 파일에 붙여 넣어 각 셀의 문자열 사이에 공백이 없도록 한 행에 표시하려고합니다.엑셀 범위를 텍스트 (.txt) 파일로 복사하는 방법, 모든 셀이 하나의 단일 문자열을 형성하고 별도의 항목이 아니도록 포맷되지 않은 경우? C#

지금 내 코드는 각 셀 항목을 자체 엔티티로 읽고 별도의 줄에 인쇄합니다. 하나의 단일 문자열을 반복 할 수 있기를 원하므로 모든 문자열을 단일 문자열로 구성하고 싶습니다.

Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass(); 
      Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(comboBox2.Text); 
      Excel.Worksheet xlWorkSheet = 

(Excel.Worksheet)excelWorkbook.Sheets[sheetSpaces]; 
      excelApp.Visible = false; 
      excelApp.ScreenUpdating = false; 
      excelApp.DisplayAlerts = false; 
      Excel.Range last = xlWorkSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing); 
      int lastUsedRow = last.Row; 
      string lastCell = "B" + lastUsedRow.ToString(); 
      Excel.Range range = xlWorkSheet.get_Range("B1", lastCell); 


      foreach (Excel.Range item in range.Cells) 
      { 

       string text = (string)item.Text; 
       if (text == "Good") 
       { 
        //get address of all Good items 
        string textx = (string)item.Address; 

    //change address of Good items to corresponing address in D column 
       string textxcorrect = textx.Replace("B", "D"); 

       //get rid of "$" for address 
       var cellAddress = textxcorrect.Replace("$", ""); 

       //create range for addresses with the new D column addresses 
       Excel.Range xlRng = xlWorkSheet.get_Range(cellAddress, Type.Missing); 
        string fileLocation = @"C:\\Users\\npinto\\Desktop\\hopethisworks.txt"; 


       foreach (Excel.Range item2 in xlRng) 
        { 
         xlRng.Copy(); 

         File.WriteAllText(fileLocation, Clipboard.GetText()); 

        } 




        string readText = System.IO.File.ReadAllText(fileLocation); 
        Console.WriteLine(readText); 
+0

파일에 쓰기 전에 클립 보드의 텍스트에 사용해보십시오 - https://stackoverflow.com/questions/5203607/fastest-way-to-remove-white-spaces-in-string 그것은 흰색을 제거 –

+0

각 개별 셀 항목의 공백은 하나의 문자열을 형성하기 위해 모든 셀 항목을 함께 연결하지 않습니다. 그들은 여전히 ​​별도의 노선에 있습니다. –

+0

바로 여기에서 성취하고자하는 것은 무엇입니까? "B"열의 셀 목록을 반복하는 것처럼 보입니다. "Good"문자열이 포함 된 각 셀에 대해 셀 주소를 다시 만든 다음 내용을 추출합니다 know는 "좋다") & 클립 보드에 복사 한 다음 파일에 추가합니다 (추가하는 대신). 길고 강한 "좋은"것을 설명했을 때 코드가 작동하면 달성 할 수있는 것 같습니다. – PaulF

답변

1

나는 원래의 질문에 따라 내 대답을 업데이트 한 - 하나의 셀이 포함됩니다 D 열에서 같은 행의 셀 - 지금 "좋은"라는 단어를 포함 할 행 B에서 제대로 셀을 이해한다면 참조 - 예 : A4 & 그 데이터를 추가하려고합니다.

주 - 열 D 셀에 "+ A4"가 포함되어 있으면 반환 할 텍스트가 추가되어야합니다. 따라서 xlRng2가 아닌 nextAddress를 연결하면됩니다.

어떨까요 - 텍스트 크기에 따라 문자열보다는 StringBuilder를 사용할 수 있지만 소량의 데이터 만 있으면 큰 차이는 없습니다.

string RequiredOutputString = String.Empty; 
foreach (Excel.Range item in range.Cells) 
{ 
    string text = (string)item.Text; 
    if (text == "Good") 
    { 
    //get address of all Good items 
    string textx = (string)item.Address; 

    //change address of Good items to corresponing address in D column 
    var cellAddress = textx.Replace("$B", "D"); 
    // get a reference to cell in column D 
    Range xlRng = curWorkSheet.get_Range(cellAddress, Type.Missing); 
    // get the cell address in row D cell 
    string nextAddr = xlRng.Text; 
    // get a reference to the cell point to from Row D 
    Range xlRng2 = curWorkSheet.get_Range(nextAddr, Type.Missing); 
    // append that cell contents 
    RequiredOutputString += xlRng2.Text.Trim(); 
    } 
} 

string fileLocation = @"C:\\Users\\npinto\\Desktop\\hopethisworks.txt"; 
File.WriteAllText(fileLocation, RequiredOutputString); 
+0

마침내 대답을 사용하여 알아 냈습니다. 감사합니다 : D "RequiredOutputString" 속임수. –