且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从数据集中检索每一行并将每一行写入单独的文本文件

更新时间:2022-10-19 20:19:13

HI Sathish



基本上你不应该直接问完整代码,你应尝试一些事情,如果你在这种方法中遇到任何困难,你可以在这里张贴相同的内容。

在此论坛中不鼓励询问代码。 :)

现在你可以尝试以下。



  string  folderLocation =  @  D:\ CodeProject\ temp;  //  保存文件的路径 
// 从数据库中获取数据并将其存储在数据集/数据表中的代码
// 假设数据表如下所示,其数据为3X3

DataTable dt = DataTable();
dt.Columns.AddRange( new DataColumn [] { new DataColumn( Column1), new DataColumn( Column2), new DataColumn( Column3)});
dt.Rows.Add( Row-1-Column-1 Row-1-Column-2 Row-1-Column-3);
dt.Rows.Add( Row-2-Column-1 Row-2-Column-2 Row-2-Column-3);
dt.Rows.Add( Row-3-Column-1 Row-3-Column-2 Row-3-Column-3);


for int i = 0 ; i < dt.Rows.Count; i ++) // 迭代每一行以获取值
{
string fileName = folderLocation + \\ + 文件 - + i + .txt; // 保存每一行的文件名
string contents = ;
foreach (DataColumn col in dt.Columns) // 迭代每一列以获得其对应的值
contents + = dt.Rows [i] [col] .ToString()+ ; // 连接内容

System.IO.File.WriteAllText(fileName ,内容); // 创建文本文件并复制内容
}


Hi,

I'm calling a Stored Procedure say 'GetUserDetails' which retrieves say 3 rows with 3 columns [3X3] with SqlCommand and this is stored in to a DataSet.

Now I wanted to loop through each row from the DataSet and write each row to a separate text file, I mean the final outcome should contain 3 text file which contains only a row of data from the dataset and save it in some location.

Can anyone help at it? Thanks.

HI Sathish

basically you are not supposed to ask the complete code directly, you shall try something and if u face any difficulty in that approach you can post the same here.
asking the code is not encouraged in this forum. :)
for now you can try the below .

string folderLocation = @"D:\CodeProject\temp"; // your path to save the files
           // code to fetch the data from DB and store it in dataset/datatable
           // assume the datatable as below , which has data in 3X3

           DataTable dt = new DataTable();
           dt.Columns.AddRange(new DataColumn[] { new DataColumn("Column1"), new DataColumn("Column2"), new DataColumn("Column3") });
           dt.Rows.Add("Row-1-Column-1", "Row-1-Column-2", "Row-1-Column-3");
           dt.Rows.Add("Row-2-Column-1", "Row-2-Column-2", "Row-2-Column-3");
           dt.Rows.Add("Row-3-Column-1", "Row-3-Column-2", "Row-3-Column-3");


           for (int i = 0; i < dt.Rows.Count; i++)  // iterate each rows to get the value
           {
               string fileName = folderLocation + "\\" +  "File-" + i + ".txt";  // file name for saving each row
               string contents = "";
               foreach (DataColumn col in dt.Columns)  // iteate each column to get its corresponding value
                   contents += dt.Rows[i][col].ToString() + "    ";  // concatenating the contents

               System.IO.File.WriteAllText(fileName, contents);  // create a text file and copy the contents
           }