2017-04-14 7 views
1

첫 번째 AddIn Excel이고 Excel 파일을 구분 기호 ("|")가있는 텍스트 파일로 내보낼 때 문제가 있습니다. 확장명이 ".txt"인 동일한 경로에서 Excel의 파일을 내보내 려는데 Excel의 열을 특정 문자 ("|")로 구분하고 싶습니다.C# AddIn Excel : 구분 기호가있는 텍스트 파일에 xls 파일을 내 보냅니다.

private void exportSave_Click(object sender, RibbonControlEventArgs e) 
    { 
     int lastColumns;   
     lastColumns = usedRange.Columns.Count; 
     int endCol = lastColumns; 

     Microsoft.Office.Interop.Excel.Worksheet xlSheet = Globals.VATTools.Application.ActiveSheet; 
     Microsoft.Office.Interop.Excel.Range usedRange = xlSheet.UsedRange; 

     // Save file in .txt in the same path 
     string path = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); 
     xlSheet.SaveAs(path, Microsoft.Office.Interop.Excel.XlFileFormat.xlTextWindows); 
    } 

나는 형식 "xlTextWindows"의 확실하지 않다 :

나는 리본의 버튼을 만들었습니다.

나는 나의 열을 식별하지만 난 그게

감사를 .txt로 내보내기 전에 열 사이의 특정 문자를 추가하는 방법을 모르겠어요!

답변

2

다음 코드를 시도 :

public static void ExportToPipe(RibbonControlEventArgs e) 
{ 
    string ExportName = @"D:\Pipe.txt"; 
    Excel.Window window = e.Control.Context; 
    Excel.Worksheet sheet = ((Excel.Worksheet)window.Application.ActiveSheet); 
    Excel.Range last = sheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing); 

    int lastUsedRow = last.Row; 
    int lastUsedColumn = last.Column; 

    string output = ""; 

    for (int i = 1; i <= lastUsedRow; i++) 
    { 
     for (int j = 1; j <= lastUsedColumn; j++) 
     { 
      if (sheet.Cells[i, j].Value != null) 
      { 
       output += sheet.Cells[i, j].Value.ToString();       
      } 
      output += "|"; 
     } 
     output += Environment.NewLine; 
    } 

    FileStream fs = new FileStream(ExportName, FileMode.Create, FileAccess.Write); 
    StreamWriter writer = new StreamWriter(fs); 
    writer.Write(output); 
    writer.Close(); 
} 
+0

감사합니다, 그것은 완벽! – user2814368