我必须在excel文件中写一个字典(Key,value pair)。我尝试过使用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
命令帮助我吗?
答案 0 :(得分:0)
选中此示例以写入excel。
http://www.codeproject.com/Articles/8500/Reading-and-Writing-Excel-using-OLEDB
OLEDB类似于您的ADO.NET SqlDataAdapter
,您可以在其中指定INSERT和UPDATE命令并使用DataTable
来插入或更新。
对于字典,您可以执行类似的操作,将Key,Value作为DataColumns并将条目添加为行
没有'检查过但你也可以执行OledbCommand作为INSERT和UPDATE并执行非查询。
希望这会有所帮助。