【发布时间】:2009-06-24 11:59:54
【问题描述】:
我需要使用 C# 将 Excel 工作表/工作簿中的数据写入文本文件。
另外,我想要一个文本文件中的所有 Excel 工作表数据。
除了从Excel表格中逐一读取数据,然后将其附加到现有的文本文件中,还有其他简单的方法吗?
【问题讨论】:
标签: c# excel text-files
我需要使用 C# 将 Excel 工作表/工作簿中的数据写入文本文件。
另外,我想要一个文本文件中的所有 Excel 工作表数据。
除了从Excel表格中逐一读取数据,然后将其附加到现有的文本文件中,还有其他简单的方法吗?
【问题讨论】:
标签: c# excel text-files
我建议使用OleDbDataReader 和来自www.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();
}
}
}
}
您可以下载免费试用版here 并亲自试用。
免责声明:我拥有 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。
【讨论】: