[英]Console app not launching via task scheduler when set to "At StartUp"
[英]Task Scheduler Not Launching Excel in Application
我編寫了一個應用程序,該應用程序可以安裝到我們的服務器上,檢查是否創建了任何待處理的作業,是否處理了所有可用的作業,創建包含結果的excel文檔,然后將其通過電子郵件發送給我們的用戶。 它使用Microsoft Excel 2010以c#.net v3.5編寫,並通過任務計划程序每30分鍾啟動一次。 我們的任務計划程序在運行2008 r2的服務器上運行。 任務計划程序成功運行,成功地更新了數據庫,就像處理了作業一樣,但是,它從未創建excel文件,而且我不知道為什么。 如果我在服務器計算機上手動運行該應用程序,則該應用程序運行順利,但是即使任務計划程序調用它也無法運行一次。 因為我是管理員,所以沒有權限問題,我甚至嘗試使用我們的IT總監憑據運行它,但無濟於事。 還要檢查該文件夾對創建/刪除/編輯/等具有完全訪問權限。 還嘗試提供到文件的絕對路徑來代替相對路徑。 可以在下面找到用於創建excel文件的代碼以及用於調用它的代碼。 提前致謝。
Excel代碼:
public static void Export(System.Data.DataTable dt,
string FileName,
string EmailTo)
{
Application xls = new Application();
xls.SheetsInNewWorkbook = 1;
// Create our new excel application and add our workbooks/worksheets
Workbooks workbooks = xls.Workbooks;
Workbook workbook = workbooks.Add();
Worksheet CompPartsWorksheet = (Worksheet)xls.Worksheets[1];
// Hide our excel object if it's visible.
xls.Visible = false;
// Turn off screen updating so our export will process more quickly.
xls.ScreenUpdating = false;
// Turn off calculations if set to automatic; this can help prevent memory leaks.
xls.Calculation = xls.Calculation == XlCalculation.xlCalculationAutomatic ? XlCalculation.xlCalculationManual : XlCalculation.xlCalculationManual;
// Create an excel table and fill it will our query table.
CompPartsWorksheet.Name = "Comp Request";
CompPartsWorksheet.Select();
{
// Create a row with our column headers.
for (int column = 0; column < dt.Columns.Count; column++)
{
CompPartsWorksheet.Cells[1, column + 1] = dt.Columns[column].ColumnName;
}
// Export our datatable information to excel.
for (int row = 0; row < dt.Rows.Count; row++)
{
for (int column = 0; column < dt.Columns.Count; column++)
{
CompPartsWorksheet.Cells[row + 2, column + 1] = (dt.Rows[row][column].ToString());
}
}
}
// Freeze our column headers.
xls.Application.Range["2:2"].Select();
xls.ActiveWindow.FreezePanes = true;
xls.ActiveWindow.DisplayGridlines = false;
// Autofit our rows and columns.
xls.Application.Cells.EntireColumn.AutoFit();
xls.Application.Cells.EntireRow.AutoFit();
// Select the first cell in the worksheet.
xls.Application.Range["$A$2"].Select();
// Turn off alerts to prevent asking for 'overwrite existing' and 'save changes' messages.
xls.DisplayAlerts = false;
// ******************************************************************************************************************
// This section is commented out for now but can be enabled later to have excel sheets show on screen after creation.
// ******************************************************************************************************************
// Make our excel application visible
//xls.Visible = true;
//// Turn screen updating back on
//xls.ScreenUpdating = true;
//// Turn automatic calulation back on
//xls.Calculation = XlCalculation.xlCalculationAutomatic;
string SaveFilePath = string.Format(@"{0}\Jobs\{1}.xlsx", Directory.GetCurrentDirectory(), FileName);
// string SaveFilePath = @"\\netapp02\Batch_Processes\Comp_Wisp\Comp_Wisp\bin\Debug\Jobs";
workbook.SaveAs(SaveFilePath, XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workbook.Close();
// Release our resources.
Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(workbooks);
Marshal.ReleaseComObject(CompPartsWorksheet);
Marshal.ReleaseComObject(xls);
Marshal.FinalReleaseComObject(xls);
Send(Subject: FileName,
AttachmentPath: SaveFilePath,
EmailTo: EmailTo);
}
調用Excel創建方法的代碼:
public static void ProcessJob(System.Data.DataTable Job)
{
try
{
for (int j = 0; j < Job.Rows.Count; j++)
{
// Temporary datatable to store our excel data.
System.Data.DataTable dt = new System.Data.DataTable();
// Output the current job name and split out our parts.
Console.Write(string.Format("JOB: {0}\r\n", Job.Rows[j]["JobID"]));
string[] searchlines = Job.Rows[j]["PartsList"].ToString().Replace("\n", "|").Split('|');
if (searchlines.Count() > MAX_TO_PROCESS)
{
// If our search is going to be above the desired processing maximum start the next job as well.
Thread RecursiveJob = new Thread(GetJob);
RecursiveJob.Start();
}
for (int i = 0; i < searchlines.Count(); i++)
{
// Determine if data reporting is turned on or off.
Boolean isReporting = DataCollection();
if (searchlines[i].Trim() != string.Empty)
{
Console.WriteLine(string.Format("Processing: {0}", searchlines[i]));
using (SqlConnection con = new SqlConnection(dbComp))
{
using (SqlDataAdapter da = Connect.ExecuteAdapter("[CompDatabase_SelectPartsFromComp]", con,
new SqlParameter("@PartNumber", searchlines[i].Trim()),
new SqlParameter("@CurrentMember", Job.Rows[j]["Email"].ToString()),
new SqlParameter("@DataCollection", isReporting)))
{
da.Fill(dt);
}
}
}
}
// Export our datatable to an excel sheet and save it.
try
{
Export(dt: dt,
FileName: string.Format("Comp Scheduled Job {0}", Job.Rows[j]["JobID"].ToString()),
EmailTo: Job.Rows[j]["Email"].ToString().Trim());
}
catch (Exception ex)
{
ErrorLog.Write(SourceName: "Comp Wisp",
ErrorMessage: ex.ToString(),
MethodOrFunction: "ProcessJob",
MemberName: Environment.UserName,
ErrorDescription: string.Format("Failed to create excel file on Job {0}.", Job.Rows[j]["JobID"].ToString()));
}
// Update the job to Complete in our database.
using (SqlConnection con = new SqlConnection(dbComp))
{
Console.WriteLine("Updating Job Status");
using (SqlDataReader dr = Connect.ExecuteReader("[CompWisp_UpdateJobStatus]", con,
new SqlParameter("@JobID", Job.Rows[j]["JobID"].ToString()))) { }
}
Console.Write("Complete\r\n\r\n");
}
GetJob();
}
catch (Exception ex)
{
ErrorLog.Write(SourceName: "CompWisp",
ErrorMessage: ex.ToString(),
MethodOrFunction: "ProcessJob");
}
}
當任務計划程序運行作業時,與手動運行應用程序時,對Directory.GetCurrentDirectory()
的調用可能返回不同的值。
要對此進行測試,您可以嘗試在服務器上搜索丟失的excel文件。
您可以嘗試以下幾種方法:
確保在其下運行任務的用戶未啟用UAC。 這可能會導致執行問題。
同樣,請參閱以下文章是否有幫助。 答案(也許)是第一個列出的答案: MSDN論壇問題 。
我無法讓Task Scheduler運行創建Excel電子表格的應用程序。 我需要創建此文件夾才能使其正常運行。 C:\\ windows \\ syswow64 \\ config \\ systemprofile \\ desktop
這是我從那里獲得信息的地方
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.