【问题标题】:how to write a dictionary to excel file using OLEDB in c#如何在 C# 中使用 OLEDB 将字典写入 excel 文件
【发布时间】:2013-03-15 10:46:15
【问题描述】:

我必须将字典(键、值对)写入 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 命令吗?

【问题讨论】:

    标签: c# excel oledb


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-31
      • 2016-03-14
      • 2021-07-10
      • 2017-08-05
      • 1970-01-01
      相关资源
      最近更新 更多