如何将参数从c发送到excel并保存在那里
本文关键字:excel 保存 在那里 参数 | 更新日期: 2023-09-27 18:21:10
我有两个问题,我正面临
-
我有一个数据集,需要将数据从数据集发送到excel一旦将数据转储到该位置。
-
我需要更改列标题,使其加粗
2:在报告标题上方,我们应该传递一个参数,该参数将是我们需要作为参数传递给它的c#中的名称(员工详细信息)。它可以改变我们传递的任何参数。
例如:报告名称:员工详细信息
Name EmpID city
Arun 11 bangalore
Kiran 56 chennai
Rahul 23 pune
下面的应该可以工作,但我没有测试它。感谢Deborah Kurata编写了下面的大部分代码。
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
private void ExportToExcel(DataTable Table, string ReportName, string Filename)
{
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
Excel.Range oRange;
// Start Excel and get Application object.
oXL = new Excel.Application();
// Set some properties
oXL.Visible = true;
oXL.DisplayAlerts = false;
// Get a new workbook.
oWB = oXL.Workbooks.Add(Missing.Value);
// Get the active sheet
oSheet = (Excel.Worksheet)oWB.ActiveSheet ;
oSheet.Name = "Report";
int rowCount = 3;
foreach (DataRow dr in Table.Rows)
{
for (int i = 1; i < Table.Columns.Count+1; i++)
{
// Add the header the first time through
if (rowCount==3)
{
oSheet.Cells[1, i] = Table.Columns[i - 1].ColumnName;
rowCount++;
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
rowCount++;
}
// Resize the columns
oRange = oSheet.get_Range(oSheet.Cells[3, 1],
oSheet.Cells[rowCount, Table.Columns.Count]);
oRange.EntireColumn.AutoFit();
// Set report title *after* we adjust column widths
oSheet.Cells[1,1] = ReportName;
// Save the sheet and close
oSheet = null;
oRange = null;
oWB.SaveAs(Filename, Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
oWB.Close(Missing.Value, Missing.Value, Missing.Value);
oWB = null;
oXL.Quit();
// Clean up
// NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}