用于读取文件夹和文件名中的所有文本文件名的代码发送到excel。
问题描述:
用于读取文件夹中所有文本文件名的代码,并创建excel文件和文件名发送到excel in c#.net
code for read all text file names in the folder and create excel file and file names send to excel in c#.net
答
读取文件名很简单:
Reading file names is pretty easy:
string[] files = Directory.GetFiles(@"D:\Temp");
如果你想要没有路径的文件名,那么添加:
If you want the filename without the path then add:
string[] justFiles = files.Select(f => Path.GetFileName(f)).ToArray();
或
string[] justFiles = files.Select(f => Path.GetFileNameWithoutExtension(f)).ToArray();
保存到Excel更复杂,但这可能有助于简化它:使用C#将数据写入Excel [ [
另一种方法是将所有文件名转换为DataTable [ ^ ]而不是使用 CopyFromRecordset方法 [ ^ ]用于MS Excel范围。 />
Another way is to get all file names into DataTable[^] and than use CopyFromRecordset method[^] for MS Excel range.
//get files into datatable
string[] filePaths = Directory.GetFiles(@"F:\\Download\\", "*.txt",SearchOption.AllDirectories);
DataTable dt = new DataTable("Files");
DataColumn dc = new DataColumn("File", Type.GetType("String"));
dt.Columns.Add(dc);
for (int i = filePaths.GetLowerBound(0); i < filePaths.GetUpperBound(0); i++)
{
DataRow dr = dt.NewRow();
dr["File"] = filePaths[i];
}
//create new workbook and insert data using CopyFromRecordset method ;)
//follow the link: http://support.microsoft.com/kb/306023
请点击以下链接:如何使用Visual C#2005或Visual C#.NET将数据传输到Excel工作簿 [ ^ ]