在这里,我仅将此代码用于选择一个文件并创建一个数据表并存储在数据集中..但我想为多个 Csv 文件创建多个数据表并存储在数据集中。最后从数据集中导出为 CSV。但这很难,请帮帮我..
//
private void button1_Click(object sender, EventArgs e)
{
int nRows = 0; //Row Counter
int icol = 0; //Index value for Columns -> fArray
int irow = 0; //Index value for Row -> fArray
string[,] fArray;
string Line; //Temp string value for storing lines
#region File Open Parameters
//file open parameters
OpenFileDialog fopen = new OpenFileDialog();
fopen.Title = "Choose file...";
fopen.Filter = "Comma Seperated Values|*.csv";
fopen.InitialDirectory = @"C:\";
#endregion
if (fopen.ShowDialog() == DialogResult.OK) //Show file open dialog and check if ok has been pressed
{
//#region progress bar initialisation
////initialize progress bar
//pb.Location = new Point(60, 209);
//pb.Width = 516;
//pb.Height = 23;
//pb.Style = ProgressBarStyle.Continuous;
//pnlStep1.Controls.Add(pb);
//#endregion
try
{
StreamReader fReader = new StreamReader(fopen.FileName);
#region Array Index Counters
//Count Columns for fArray index
string count = fReader.ReadLine();
string[] tmpCount = count.Split(',');
fReader.Close();
//Count Rows for fArray index
fReader = new StreamReader(fopen.FileName); //begin reading from line 1
while ((fReader.ReadLine()) != null)
{
nRows++;
}
fArray = new string[nRows, tmpCount.Length];
fReader.Close();
//End count
#endregion
#region Load File Contents
fReader = new StreamReader(fopen.FileName); //begin reading from line 1
DataSet ds = new DataSet();
dt = ds.Tables.Add("ImportData");
while ((Line = fReader.ReadLine()) != null)
{
string[] row = Line.Split(',');
foreach (string column in row)
{
fArray[irow, icol] = column;
icol++;
}
icol = 0;
////recordCountLabel.Text = irow.ToString(); //NEEDS LOOKING AT
////pb.Value = (irow * 100) / fArray.GetLength(0);
irow++;
}
//pb.Value = 100;
fReader.Close();
#endregion
#region Add data to dgImport
for (int i = 0; i < fArray.GetLength(1); i++) //Add Columns to empty DataGridView
{
dt.Columns.Add(fArray[0,i]);
}
for (int i = 1; i < fArray.GetLength(0); i++) //Insert data into DataGridView (use fArray.GetLength(0) for entire database or use 5 for sample data)
{
DataRow row = dt.NewRow();
for (int j = 0; j < fArray.GetLength(1); j++)
{
row[j] = fArray[i, j].Trim();
}
dt.Rows.Add(row);
dataGridView1.DataSource = dt;
}
#endregion
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk.\r\nOriginal error: " + ex.Message);
}
}
}