簡體   English   中英

C#AddIn Excel:使用分隔符在文本文件中導出xls文件

[英]C# AddIn Excel : export xls file in text file with separator

這是我的第一個AddIn excel,在導出帶有分隔符(“ |”)的文本文件中的excel文件時遇到了問題。 我想以相同的路徑導出excel文件,擴展名為“ .txt”,並且我想用特定字符(“ |”)分隔excel的列。

我在功能區上創建了一個按鈕:

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之前不知道如何在列之間添加特定字符

謝謝 !

試試下面的代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM