簡體   English   中英

使用C#將數據從Excel工作表寫入文本文件

[英]Write the data from an Excel sheet to the text file using C#

我需要使用C#將數據從Excel工作表/工作簿寫入文本文件。

另外,我希望所有Excel工作表數據都在單個文本文件中。

除了一張一張地讀取Excel工作表中的數據,然后將其附加到現有的文本文件之外,還有其他簡單的方法嗎?

我建議將OleDbDataReaderwww.connectionstrings.com的連接字符串一起使用以讀取Excel文件。 您可以使用自己喜歡的方法,例如StreamWriter ,將數據吐出到文本文件中。

SpreadsheetGear for .NET可以使用幾行代碼來實現:

using System;
using SpreadsheetGear;

namespace WorkbookToCSV
{
    class Program
    {
        static void Main(string[] args)
        {
            string inputFilename = @"c:\CSVIn.xlsx";
            string outputFilename = @"c:\CSVOut.csv";
            // Create the output stream.
            using (System.IO.FileStream outputStream = new System.IO.FileStream(outputFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write))
            {
                // Load the source workbook.
                IWorkbook workbook = Factory.GetWorkbook(inputFilename);
                foreach (IWorksheet worksheet in workbook.Worksheets)
                {
                    // Save to CSV in a memory buffer and then write it to
                    // the output FileStream.
                    byte[] csvBuffer = worksheet.SaveToMemory(FileFormat.CSV);
                    outputStream.Write(csvBuffer, 0, csvBuffer.Length);
                }
                outputStream.Close();
            }
        }
    }
}

您可以在此處下載免費試用版,然后自己嘗試。

免責聲明:我擁有SpreadsheetGear LLC

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Globalization;

namespace Module2
{
    public class Archives
    {
        public void readArchive()
        {
            //this will read from the archive
            StreamReader SR;
            string S;
            int i = 0;
            SR = File.OpenText(@"the path here for the excel archive");

            S = SR.ReadToEnd();
            SR.Close();
            Console.WriteLine(S);
            string[] words = S.Split(';');
            Array.Sort(words);
            for (i = 0; i < words.Length; i++)
                Console.WriteLine(words[i]);

            //this will create the archive
            StreamWriter SW;
            SW = File.CreateText(@"the path here for the .txt");
            for (i = 0; i < words.Length; i++)
                SW.WriteLine(words[i]);
            SW.Close();
        }
    }
}

將讀取,拆分文本並將其放置在數組上,並將每個單詞寫到.txt文件中。

有很多方法可以做到這一點。 嘗試在搜索框中搜索Excel。

在您的情況下,我認為最簡單的選擇是使Excel自動化以打開excel工作簿,然后使用SaveAs函數將其另存為CSV。

暫無
暫無

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

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