[英]How to write datatable rows to multiple files N number of records at a time?
I have a query that pulls an unknown number of rows in to a datatable.我有一个查询将未知数量的行拉入数据表。 I need to write the datatable to multiple tabbed delimited text files with only 55 rows per file.我需要将数据表写入多个标签分隔的文本文件,每个文件只有 55 行。 Desired results Ex.期望的结果 例如。 176 records from query.来自查询的 176 条记录。 File1 - 55 records, File2 - 55 records, File3 - 55 records, File6 - 11 records. File1 - 55 条记录,File2 - 55 条记录,File3 - 55 条记录,File6 - 11 条记录。 I am not sure the best way to do this.我不确定执行此操作的最佳方法。 Any help would be greatly appreciated.任何帮助将不胜感激。
Current Code:当前代码:
DataTable results = sql results;
if (results.Rows.Count > 0)
{
int counter = 0;
int maxRows = 55;
string fileName = path + "File_" + today.ToString("yyyyMMdd") + ".txt";
if (File.Exists(fileName))
{
File.Delete(fileName);
}
for (int i = 0; i < results.Rows.Count; i++)
{
var currentRow = results.Rows[i];
_writer.WriteDataToFile(results, fileName, delimiter); //This method writes a datatable to a file
counter = counter + i;
}
}
Try following:尝试以下操作:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
namespace ConsoleApplication190
{
class Program
{
const string PATH = @"Enter Path Here";
const int NUMBER_ROWS = 55;
static void Main(string[] args)
{
DataTable results = new DataTable();
DateTime today = DateTime.Now.Date;
if (results.Rows.Count > 0)
{
int filenumber = 0;
int rowCount = 0;
StreamWriter writer = null;
foreach (DataRow row in results.AsEnumerable())
{
if (rowCount % NUMBER_ROWS == 0)
{
if (writer != null)
{
writer.Flush();
writer.Close();
}
string fileName = PATH + "File_" + ++filenumber + "_" + today.ToString("yyyyMMdd") + ".txt";
writer = new StreamWriter(fileName);
}
writer.WriteLine(string.Join("\t", row.ItemArray));
rowCount++;
}
writer.Flush();
writer.Close()
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.