私はExcelテンプレートにダンプするストアドプロシージャを実行します。Excelに直接データテーブルC#
現在動作していますが、時間がかかりすぎます。 SQL Server Management Studioでは、クエリはうまく動作しますが、テンプレートに書き込むときには、実際には遅いです。
誰も同じ結果を達成するためのより効率的な方法を提案できますか?ここで
は、私のコードの一部です:
sdate = StartDate.Value.ToString();
edate = EndDate.Value.ToString();
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet aSheet;
try
{
//Start Excel and get Application object.
oXL = new Excel.Application();
oXL.Visible = true;
//open the excel template
oWB = oXL.Workbooks.Open("C:\\TEMP\\template.xlsm");
//oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
//Call to service
//aSheet = (Excel._Worksheet)oWB.Worksheets.get_Item(1);
aSheet = (Excel._Worksheet)oWB.ActiveSheet;
//backgroundWorker1.ReportProgress(i++);
writedata_from_proc(aSheet, "dbo.CODE_RED_2017");
//backgroundWorker1.ReportProgress(i++);
//Make sure Excel is visible and give the user control
//of Microsoft Excel's lifetime.
//backgroundWorker1.ReportProgress(i++);
MessageBox.Show("Data extraction complete");
oXL.Visible = true;
oXL.UserControl = true;
//SaveExcel(oWB);
//clean up the COM objects to remove them from the memory
Marshal.FinalReleaseComObject(aSheet);
Marshal.FinalReleaseComObject(oWB);
Marshal.FinalReleaseComObject(oXL);
}
catch (Exception theException)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);
MessageBox.Show(errorMessage, "Error");
}
}
ここで私が最初に逃したコードです:
public void writedata_from_proc(Excel._Worksheet oWS,string sentproc)
{
int rowCount = 0;
SqlCommand cmd = new SqlCommand(sentproc.ToString());
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@start_date", SqlDbType.DateTime).Value = getsdate();
cmd.Parameters.Add("@end_date",SqlDbType.DateTime).Value=getedate();
cmd.CommandTimeout = 0;
DataTable dt = GetData(cmd);
oWS.UsedRange.Rows.Count.ToString();
if (sentproc.Contains("CODE_RED"))
{
rowCount = 1;
}
else
{
rowCount = oWS.UsedRange.Rows.Count;
}
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
// Add the header the first time through
if (rowCount == 2)
{
oWS.Cells[1, i] = dt.Columns[i - 1].ColumnName;
}
oWS.Cells[rowCount, i] = dr[i - 1];
}
}
}
このwritedata_from_procメソッドは何ですか?それのソースコードは何ですか? –
** 'writedata_from_proc' **のメインコードは含まれていません。 – ManishChristian
「あまりにも長くかかる」と定義します。 –