[英]how to send paramter from c# to excel and save the data there
i have 2 issues what i am facing 我面临2个问题
i have an dataset where i need to send the data from dataset to an excel once data in dumped in that location. 我有一个数据集,一旦将数据转储到该位置,我就需要将数据从数据集发送到Excel。
i need to change the column headers make them bold 我需要更改列标题使其变为粗体
2: Above the report headers we should pass 1 parameter that will be the name(Employee details) from c# we need to pass as an parameter to it. 2:在报告标题上方,我们应该传递1个参数,该参数将是我们需要作为参数传递给c#的名称(员工详细信息)。 it can change what ever parameter we pass it on.
它可以更改我们传递给它的参数。
ex: Reportname: Employee details 例如:报告名称:员工详细信息
Name EmpID city
Arun 11 bangalore
Kiran 56 chennai
Rahul 23 pune
The following should work, but I did not test it. 以下应该工作,但我没有对其进行测试。 Thank you to Deborah Kurata for writing a large part of the code below.
感谢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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.