0

我正在使用 LINQ 进行导入和导出。导入工作正常。但是在导出相同的文件时我遇到了一些问题。

有 13 个表,所以我导入 13 个 csv 文件。现在我将相同的文件导入数据库,但一个表有逗号分隔的数据。

喜欢(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