0

我必须将字典(键、值对)写入 excel 文件。我试过使用Interop.Excel并写过这样的:

try
{
    string file =@”D:\Someexcel.xls”
    Interop.Excel.Application excelApp = new Interop.Excel.Application();
    excelApp.Visible = true;
    Interop.Excel.Workbook wb = excelApp.Workbooks.Open(file, Type.Missing, Type.Missing,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
        Type.Missing, Type.Missing);
    Interop.Excel.Worksheet ws = wb.ActiveSheet as Interop.Excel.Worksheet;
    Interop.Excel.Range rng = ws.get_Range("A1", Type.Missing);

    //Write Key, Value as header
    ws.Cells[1, 1] = "Key";
    ws.Cells[1, 2] = “Value”;

    int row = 2; // Initialize for keys.
    foreach (string key in dict.Keys)
    {
        int column = 1; // Initialize for values in key.
        ws.Cells[row, column] = key;
        column++;
        ws.Cells[row, column] = dict[key];
        row++;
    }

    if (ws != null)
        Marshal.ReleaseComObject(ws);
    if (wb != null)
        Marshal.ReleaseComObject(wb);
    if (excelApp != null)
        Marshal.ReleaseComObject(excelApp);
    DialogResult result = MessageBox.Show(string.Format("Excel file created , you can find the file @" + file));
    if (result == DialogResult.OK)
        this.Close();
}
catch (Exception err)
{
    string msg;
    msg = "Error:";
    msg = string.Concat(msg, err.Message);
    msg = string.Concat(msg, "Line:");
    msg = string.Concat(msg, err.Source);
    MessageBox.Show(msg);
}

但是,这段代码似乎更频繁地中断,而不是说服务器位置上的 excel 文件已损坏。所以,我想试试OLEDB。我是 OLEDB 的新手。在互联网上到处搜索,但没有关于如何编写字典的信息。你能帮我用Insert命令吗?

4

1 回答 1

0

检查此示例以写入 excel。
http://www.codeproject.com/Articles/8500/Reading-and-Writing-Excel-using-OLEDB
OLEDB 类似于您的 ADO.NET,SqlDataAdapter您可以在其中指定 INSERT 和 UPDATE 命令并使用 aDataTable来插入或更新。对于字典,您可以执行类似的操作,将 Key、Value 作为您的 DataColumns 并将条目添加为行。
Havent 已检查,但您也可以将 OledbCommand 作为 INSERT 和 UPDATE 执行并作为非查询执行。希望这可以帮助。

于 2013-03-15T11:16:25.363 回答