using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default2 : System.Web.UI.Page
{
//Declare and initialize variables - Already Completed
private string filename = "", SQL_Inventory = "", SQL_WorkOrder = "", SQL_PriceList="";
public SqlCommand dbCmd;
public SqlDataReader myReader;
public string strConnect = System.Configuration.ConfigurationManager.AppSettings["connectString"];
public SqlConnection dbConn = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
//Debugging help
errLabel.Text = " Error List: ";
}
//////////////////////////////////////////////////////////////////////////////////
// DownloadFile Function - Already Completed
/////////////////////////////////////////////////////////////////////////////////*/
protected void DownloadFile()
{
//////////////////////////////////////////////////////////////////////////////////
// Produce file download box
// *** If you get an error that points to Response.WriteFile(filename.ToString());
// *** as the problem, comment out this block of code. It's probably NOT a problem
// *** with writing the file. After you comment out this block, another error
// *** should appear.
//////////////////////////////////////////////////////////////////////////////////
//Debugging help
errLabel.Text += "
Downloading file...";
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + filename.ToString());
Response.WriteFile(filename.ToString());
Response.End();
//////////////////////////////////////////////////////////////////////////////////
// End Produce file download box
/////////////////////////////////////////////////////////////////////////////////*/
}
//////////////////////////////////////////////////////////////////////////////////
// GenerateInventory Function
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
// GenerateWorkOrder Function
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
// GeneratePriceListHistory Function
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
// RemoveFiles Function - Already Completed
//////////////////////////////////////////////////////////////////////////////////
private void RemoveFiles(string strPath)
{
//Debugging help
errLabel.Text += "
Removing old files...";
//Remove files older than an hour so that they don't pile up on the server
System.IO.DirectoryInfo di = new DirectoryInfo(strPath);
FileInfo[] fiArr = di.GetFiles();
foreach (FileInfo fri in fiArr)
{
if (fri.Extension.ToString() == ".xls" || fri.Extension.ToString() == ".csv")
{
TimeSpan min = new TimeSpan(0, 0, 60, 0, 0);
if (fri.CreationTime < DateTime.Now.Subtract(min))
{
fri.Delete();
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////
// CreateExcelWorkbook Function
/////////////////////////////////////////////////////////////////////////////////*/
private void CreateExcelWorkbook(string sql)
{
//Debugging help
errLabel.Text += "
Creating Excel Workbook...";
string strCurrentDir = Server.MapPath(".") + "\\";
string firstColumn="", lastColumn="";
RemoveFiles(strCurrentDir); // utility method to clean up old files
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;
try
{
GC.Collect(); // clean up any other excel guys hangin' around...
oXL = new Excel.Application();
oXL.Visible = false;
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
//get our Data
SQL_Inventory = sql;
dbCmd = new SqlCommand(SQL_Inventory, dbConn);
myReader = dbCmd.ExecuteReader();
//////////////////////////////////
// Create Header...
// GetName() gets the column name
//////////////////////////////////
//Debugging help
errLabel.Text += "
Creating Header Row...";
// Column A
// Column B
// Column C
// Column D
// Column E
// Column F
// Column G
// Column H
// Column I
//////////////////////////////////
// End Create Header
//////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// Make header row text bold & set background colors and borders
// Note the use of get_Range - gets the range from A2-I2 or A3-I3, etc
// Note the use of xlEdgeBottom, xlEdgeLeft, xlEdgeRight, xlInsideVertical
// Note the use of Color, LineStyle, Weight
// Note the use of System.Drawing to identify a color
// Note the bottom edge uses xlThick for this header row
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// End make header row text bold & set background colors and borders
///////////////////////////////////////////////////////////////////////////
/////////////////////////////
// Write out rest of data
/////////////////////////////
//Debugging help
errLabel.Text += "
Creating Rest of Spreadsheet...";
int jRow = 2;
while (myReader.Read())
{
///////////////////////////////////////////////////////////////////////////
// Write data to cells of spreadsheet
// Column C is left blank to demonstrate (later in the code) how to
// format an entire column at once.
// GetValue() gets the value from that column
///////////////////////////////////////////////////////////////////////////
// Column A
// Column B
// Column C
// Column D
// Column E
// Column F
// Column G
// Column H
// Column I
///////////////////////////////////////////////////////////////////////////
// End write data to cells of spreadsheet
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// Create vars to identify first and last cells
// This part is not dynamic... if you wanted to make this dynamic
// you would have to figure out how many columns you are creating
// in the spreadsheet and programmatically figure out what letter
// is associated with that last column.
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// End create vars to identify first and last cells
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// Make every other row light blue
// Note the use of get_Range - gets the range from A2-I2 or A3-I3, etc
// Note the use of System.Drawing.ColorTranslator.FromHtml for Hex values
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// End make every other row light blue
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// Add borders around every row
// Note the use of get_Range - gets the range from A2-I2 or A3-I3, etc
// Note the use of xlEdgeBottom, xlEdgeLeft, xlEdgeRight, xlInsideVertical
// Note the use of Color, LineStyle, Weight
// Note the use of System.Drawing to identify a color
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// End add borders around every row
///////////////////////////////////////////////////////////////////////////
//increment jRow
jRow++;
} // end while loop
/////////////////////////////
// End write out rest of data
/////////////////////////////
/////////////////////////////
// Close myReader object
/////////////////////////////
/////////////////////////////
// End close myReader object
/////////////////////////////
//Debugging help
errLabel.Text += "
Formatting Document...";
/////////////////////////////
// Set cell alignment
/////////////////////////////
/////////////////////////////
// End set cell alignment
/////////////////////////////
/////////////////////////////
// Autofit columns
/////////////////////////////
/////////////////////////////
// End autofit columns
/////////////////////////////
/////////////////////////////
// Bold the ProductNumber
/////////////////////////////
/////////////////////////////
// End bold the ProductNumber
/////////////////////////////
/////////////////////////////
// Center column E
/////////////////////////////
/////////////////////////////
// End center the Shelf & Bin
/////////////////////////////
/////////////////////////////
// Set width of column C
/////////////////////////////
/////////////////////////////
// End set width of column C
/////////////////////////////
//////////////////////////////////////////
// Set background & color of column C
// jRow-1 equals the last row
//////////////////////////////////////////
//////////////////////////////////////////
// End set background & color of column C
//////////////////////////////////////////
//////////////////////////////////////////
// Save the file - Already Completed
//////////////////////////////////////////
//Debugging help
errLabel.Text += "
Saving File...";
oXL.Visible = false;
oXL.UserControl = false;
filename = "report" + System.DateTime.Now.Ticks.ToString() + ".xls";
oWB.SaveAs(strCurrentDir + filename, Excel.XlFileFormat.xlWorkbookNormal, null, null, false, false, Excel.XlSaveAsAccessMode.xlShared, false, false, null, null, null);
//////////////////////////////////////////
// End save the file
//////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// Pause: Make sure the file is saved to server before attempting to
// download the file - Already Completed
///////////////////////////////////////////////////////////////////////////
DateTime startTime = DateTime.Now;
for (int m = 0; m < 30000; m++)
{
for (int n = 0; n < 50000; n++)
{
int p = 2 + 2;
p = p + 1;
}
}
DateTime stopTime = DateTime.Now;
TimeSpan duration = stopTime - startTime;
///////////////////////////////////////////////////////////////////////////
// Response.Write("End pause...paused for: "+duration.ToString()+"
");
// End pause
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// Need all following code to clean up and extinguish all references!!!
// Already Completed
///////////////////////////////////////////////////////////////////////////
//Debugging help
errLabel.Text += "
Cleaning up References...";
dbConn.Close();
oWB.Close(null, null, null);
oXL.Workbooks.Close();
oXL.DisplayAlerts = false;
oXL.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oRng);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oXL);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oWB);
dbConn = null;
oSheet = null;
oWB = null;
oXL = null;
oRng = null;
GC.Collect(); // force final cleanup!
GC.WaitForPendingFinalizers();
///////////////////////////////////////////////////////////////////////////
// End clean up and extinguish all references!!!
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// Kill the Excel Process - Already Completed
// In case the above lines didn't accomplish the task...
///////////////////////////////////////////////////////////////////////////
foreach(Process x in System.Diagnostics.Process.GetProcessesByName("EXCEL"))
{
x.Kill();
}
///////////////////////////////////////////////////////////////////////////
// End kill the Excel Process
///////////////////////////////////////////////////////////////////////////
// Call function to force a file download dialog box
DownloadFile();
}//end try
catch (Exception theException)
{
//Already Completed
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);
errorMessage = String.Concat(errorMessage, theException.StackTrace);
errorMessage = String.Concat(errorMessage, theException.Data);
errLabel.Text += "
"+errorMessage.ToString();
}//end catch
}//end CreateExcelWorkbook
}