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