0

LINQを使用してインポートとエクスポートを行っています。インポートは正常に機能します。しかし、同じファイルをエクスポートするときに問題が発生します。

13 個のテーブルがあるので、13 個の csv ファイルをインポートします。同じファイルをデータベースにインポートしますが、1 つのテーブルにはカンマ区切りのデータがあります。

(a、b、c) のように。

このテーブルのデータをインポートすると、Excel ファイルに新しい列が作成されます。このファイルをインポートすると、エラーが発生します。

入力配列は、このテーブルの列数よりも長くなっています。

これが私のコードです:

書き出す

string fileName = mt.TableName.Replace("dbo.", "") + "_" + TenantID + ".csv";
StreamWriter writer = new StreamWriter(filePath + fileName);

for (int j = 0; j < gd.HeaderRow.Cells.Count; j++)
{
    if (gd.HeaderRow.Cells[j].Text == "&nbsp;")
        gd.HeaderRow.Cells[j].Text = "";
    writer.Write(gd.HeaderRow.Cells[j].Text);
    if (j != gd.HeaderRow.Cells.Count)
    {
        writer.Write(",");
    }
}
writer.Write(sw.NewLine);

for (int i = 0; i < gd.Rows.Count; i++)
{
    for (int j = 0; j < gd.Rows[i].Cells.Count; j++)
    { 
        if (gd.Rows[i].Cells[j].Text == "&nbsp;")
            gd.Rows[i].Cells[j].Text = "";

        writer.Write(Convert.ToString(gd.Rows[i].Cells[j].Text));

        if (j != gd.Rows[i].Cells.Count)
        {
            writer.Write(",");
        }
    }
    writer.Write(sw.NewLine);
}
writer.Flush();
writer.Close();

輸入

// Prepare for the data to be processed into a DataTable
// We don't know how many records there are in the .csv, so we
// use a List<string> to store the records in it temporarily.
// We also prepare a DataTable;
List<string> rows = new List<string>();

// Then we read in the raw data
StreamReader reader = new StreamReader(path, true);
string record = reader.ReadLine();
string[] column = record.Split(',');
List<string> c = column.ToList<string>();
c.RemoveAll(a => string.IsNullOrEmpty(a));
column = c.ToArray();
while (record != null)
{
    rows.Add(record);
    record = reader.ReadLine();
}

// And we split it into chunks.
// Note that we keep track of the number of columns
// in case the file has been tampered with, or has been made
// in a weird kind of way (believe me: this does happen)

// Here we will store the converted rows
List<string[]> rowObjects = new List<string[]>();

int maxColsCount = 0;
foreach (string s in rows)
{
    string[] convertedRow = s.Split(new char[] { separator });
    List<string> y = convertedRow.ToList<string>();
    y.RemoveAll(p => string.IsNullOrEmpty(p));
    convertedRow = y.ToArray();

    if (convertedRow.Length > maxColsCount)
    maxColsCount = convertedRow.Length;
    rowObjects.Add(convertedRow);
}

// Then we build the table
table = new DataTable(tableName);
foreach (string col in column)
{
    table.Columns.Add(new DataColumn(col));
}

int j = 0;
foreach (string[] rowArray in rowObjects)
{
    if (j != 0)
        table.Rows.Add(rowArray);
    j = j + 1;
}
table.AcceptChanges();
4

0 に答える 0