Way too slow C# Console application. Any way to speed it up? - c#

I am currently developing a little program that goes through an excel file and escalate things by e-mail, and shows the progress of the materials in a "progress bar" inside the excel.
The program runs just fine, does all the things it intended to do but its way too slow.
For about 11 rows it takes like 3 minutes.
The file will have more and more (couple hunderd) lines eventually and it will take forever to update.
Do you guys know any way to speed this up?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using System.IO;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace Prod_Tracking
{
class Program
{
static void Main(string[] args)
{
Outlook.Application app = new Outlook.Application();
Outlook.MailItem mailItem = app.CreateItem(Outlook.OlItemType.olMailItem);
string rootPath = Directory.GetCurrentDirectory();
string path = rootPath + "\\ProdTracking.xlsx";
string email1 = "email#email.com";
string email2 = "email#email.com";
string body;
string subject;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb = excel.Workbooks.Open(path);
Microsoft.Office.Interop.Excel.Worksheet tracking = excel.Sheets["Tracking"] as Microsoft.Office.Interop.Excel.Worksheet;
Microsoft.Office.Interop.Excel.Worksheet coois = excel.Sheets["COOIS"] as Microsoft.Office.Interop.Excel.Worksheet;
Microsoft.Office.Interop.Excel.Worksheet line = excel.Sheets["Line"] as Microsoft.Office.Interop.Excel.Worksheet;
Microsoft.Office.Interop.Excel.Worksheet stat = excel.Sheets["Stat"] as Microsoft.Office.Interop.Excel.Worksheet;
Excel.Range trackingRange = tracking.UsedRange;
int mainRows = trackingRange.Rows.Count; //row number of main sheet
coois.Select(true);
Excel.Range cooisRange = coois.UsedRange;
int cooisRows =cooisRange.Rows.Count; //row number of coois sheet
line.Select(true);
Excel.Range lineRange = line.UsedRange;
int lineRows = lineRange.Rows.Count; //row number of line sheet
line.Select(true);
Excel.Range statRange = stat.UsedRange;
int statRows = statRange.Rows.Count; //row number of stat sheet
DateTime thisDay = DateTime.Today;
int days = 0;
int daysofescalation = 0;
for (int i = 3; i <= mainRows; i++)
{
double percent = (i - 2) * 100 / (mainRows - 1); //progress percentage
Console.Clear();
Console.Write("Update in progress! Please wait..." + '\n' + percent + "%" );
for(int j = 2; j <= cooisRows; j++)
{
//get data from COOIS
if (coois.Cells[j,1].Value == tracking.Cells[i, 1].Value)
{
tracking.Cells[i, 2].Value = coois.Cells[j, 2].Value;
tracking.Cells[i, 5].Value = coois.Cells[j, 11].Value;
tracking.Cells[i, 7].Value = coois.Cells[j, 8].Value;
tracking.Cells[i, 8].Value = coois.Cells[j, 9].Value;
if ((thisDay - Convert.ToDateTime(tracking.Cells[i, 5].Value)).TotalDays > 0)
{
tracking.Cells[i, 38].Value = (thisDay - Convert.ToDateTime(tracking.Cells[i, 5].Value)).TotalDays; //calculate passed time in days format
days = Convert.ToInt32(tracking.Cells[i, 38].Value);
}
else
{
tracking.Cells[i, 38].Value = "Prod not yet started";
}
//A/B/C
if (Convert.ToString(tracking.Cells[i,2].Value).Length > 12)
{
tracking.Cells[i, 3].Value = "A";
tracking.Cells[i, 6].Value = Convert.ToDateTime(tracking.Cells[i, 5].Value).AddDays(21);
tracking.Range["J" + i + ":" + "AK" + i].Interior.ColorIndex = 0; //clear progress bar/line
tracking.Range["AF" + i + ":" + "AK" + i].Interior.ColorIndex = 1; //insert black part
//fill up progress bar
if (Convert.ToString(tracking.Cells[i, 38].Value) != "Prod not yet started")
{
if (days > 21)
{
tracking.Range["J" + i + ":" + "AE" + i].Interior.ColorIndex = 3;
}
else
{
tracking.Range[tracking.Cells[i, 10], tracking.Cells[i, (10 + days)]].Interior.ColorIndex = 4;
}
}
}
if(Convert.ToString(tracking.Cells[i, 2].Value).Length == 12)
{
tracking.Cells[i, 3].Value = "B";
tracking.Cells[i, 6].Value = Convert.ToDateTime(tracking.Cells[i, 5].Value).AddDays(13);
tracking.Range["J" + i + ":" + "AK" + i].Interior.ColorIndex = 0; //clear progress bar/line
tracking.Range["W" + i + ":" + "AK" + i].Interior.ColorIndex = 1; //insert black part
//fill up progress bar
if (Convert.ToString(tracking.Cells[i, 38].Value) != "Prod not yet started")
{
if (days >= 13)
{
tracking.Range["J" + i + ":" + "V" + i].Interior.ColorIndex = 3;
}
else
{
tracking.Range[tracking.Cells[i, 10], tracking.Cells[i, (10 + days)]].Interior.ColorIndex = 4;
}
}
}
if (Convert.ToString(tracking.Cells[i, 2].Value)[0] == '5')
{
tracking.Cells[i, 3].Value = "C";
tracking.Range["J" + i + ":" + "AK" + i].Interior.ColorIndex = 0; //clear progress bar/line
tracking.Cells[i, 6].Value = Convert.ToDateTime(tracking.Cells[i, 5].Value).AddDays(28);
//fill up progress bar
if (Convert.ToString(tracking.Cells[i, 38].Value) != "Prod not yet started")
{
if (days > 28)
{
tracking.Range["J" + i + ":" + "AK" + i].Interior.ColorIndex = 3;
}
else
{
tracking.Range[tracking.Cells[i, 10], tracking.Cells[i, (10 + days)]].Interior.ColorIndex = 4;
}
}
}
//get current production status
for (int l = 2; l <= statRows; l++)
{
if(tracking.Cells[i,1].Value == stat.Cells[l,1].Value && stat.Cells[l, 7].Value != null)
{
tracking.Cells[i, 9].value = Convert.ToString(stat.Cells[l, 4].Value);
l = statRows + 1;
}
}
//Get lines (way too slow, need to be optimised, maybe import it to a list?)
for (int k = 2; k <= lineRows; k++)
{
if (tracking.Cells[i, 2].Value == line.Cells[k, 1].Value)
{
tracking.Cells[i, 4].Value = line.Cells[k, 2].Value;
k = lineRows + 1;
}
}
if (tracking.Cells[i, 4].Value == null)
{
tracking.Cells[i, 4].Value = "NA";
}
//overdue status "YES" or "NO"
if(tracking.Cells[i, 10].Interior.ColorIndex == 3)
{
tracking.Cells[i, 39].Value = "Yes";
}
else
{
tracking.Cells[i, 39].Value = "No";
}
//escalation level one, making the body into a string, sending email and writing in the date of the escalation
if(tracking.Cells[i, 39].Value == "Yes" && tracking.Cells[i, 40].Value == null && tracking.Cells[i, 42].Value != "x")
{
body = "Dear Recipient," + "\n\nThe production order: " + Convert.ToString(tracking.Cells[i, 1].Value) + " for the material " + Convert.ToString(tracking.Cells[i, 2].Value) + " is overdue." + "\nOrdered quantity: " + Convert.ToString(tracking.Cells[i, 7].Value) + "\nConfirmed quantity: " + Convert.ToString(tracking.Cells[i, 8].Value) + "\nPlease take some actions." + "\n\n\n\nThis is an automatically generated message by the production tracking tool";
subject = Convert.ToString(tracking.Cells[i, 1].Value) + " production order is overdue - Escalalation I.";
Program.SendEMail(email1, subject, body);
tracking.Cells[i, 40].Value = thisDay;
}
//escalation level2
if (tracking.Cells[i, 40].Value != null)
{
daysofescalation = Convert.ToInt32((thisDay - Convert.ToDateTime(tracking.Cells[i, 40].Value)).TotalDays);
if(daysofescalation > 8 && tracking.Cells[i, 42].Value != "x" && tracking.Cells[i, 41].Value != null)
{
body = "Dear Recipient," + "\n\nThe production order: " + Convert.ToString(tracking.Cells[i, 1].Value) + " for the material " + Convert.ToString(tracking.Cells[i, 2].Value) + " is overdue." + "\nOrdered quantity: " + Convert.ToString(tracking.Cells[i, 7].Value) + "\nConfirmed quantity: " + Convert.ToString(tracking.Cells[i, 8].Value) + "\nPlease take some actions." + "\n\n\n\nThis is an automatically generated message by the production tracking tool";
subject = Convert.ToString(tracking.Cells[i, 1].Value) + " production order is overdue - Escalalation II.";
Program.SendEMail(email2, subject, body);
tracking.Cells[i, 41].Value = thisDay;
}
}
j = cooisRows + 1;
}
}
}
wb.Close(true);
excel.Quit();
Console.Clear();
Console.WriteLine("Update in progress!Please wait..." + '\n' + "100" + " % " + "\nExcel updated!");
Console.ReadLine();
}
static void SendEMail(string email, string subject, string body)
{
Outlook.Application app = new Outlook.Application();
Outlook.MailItem mailItem = app.CreateItem(Outlook.OlItemType.olMailItem);
mailItem.Subject = subject;
mailItem.To = email;
mailItem.Body = body;
mailItem.Importance = Outlook.OlImportance.olImportanceHigh;
mailItem.Display(false);
((Outlook._MailItem)mailItem).Send();
}
}
}
Thank you so much for the help in advance,
-B

Related

C# - Copying Excel to Word using Interop

I want to copy excel to word as a picture without using the clipboard.
The clipboard is too easy for the user to manipulate while the program is running and it sometimes misses items.
How do I do this?
Heres How I handle it now
foreach (Worksheet WS in WB.Worksheets)
{
progresspercent += steps;
worker.ReportProgress(progresspercent);
if (WS.UsedRange.Count > 1 && WS != null)
{
Thread.Sleep(1000);
var height = WS.UsedRange.Height;
var width = WS.UsedRange.Width;
var MaxHeight = ((double)width * 8.5) / 6.5;
var heightRatio= (double)height/MaxHeight;
double TotalHeight = 0;
int RowsSoFar = 0;
int TotalRows = WS.UsedRange.Rows.Count;
int RowStart = 1;
int RowEnd = RowStart + (int)Math.Floor(TotalRows/heightRatio);
if (RowEnd > TotalRows + 1) { RowEnd = TotalRows + 1; }
///Calculate Image sizes and size copy for page
while (TotalRows > RowsSoFar)
{
Range CopyRange = WS.Range["A" + RowStart.ToString() + ":F" + RowEnd.ToString()];
double SelectionHeight = (double)CopyRange.Height;
while (SelectionHeight > MaxHeight )
{
//***************************************//
RowEnd = RowEnd - 1;
CopyRange = WS.Range["A" + RowStart.ToString() + ":F" + RowEnd.ToString()];
SelectionHeight = (double)CopyRange.Height;
}
FullWordDoc.Words.Last.InsertBreak(Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak);
string ContinuedPrompt = "";
if (RowStart!=1) { ContinuedPrompt = " (Continued)"; }
FullWordDoc.Words.Last.InsertAfter(WS.Name + ContinuedPrompt + "\r");
CopyRange.CopyPicture();
FullWordDoc.Words.Last.Paste();
Console.WriteLine(WS.Name);
RowsSoFar = RowsSoFar + RowEnd - RowStart + 1;
RowStart = RowEnd + 1;
RowEnd = RowStart + (int)Math.Floor(TotalRows / heightRatio);
if (RowEnd > TotalRows + 1) { RowEnd = TotalRows + 1; }
}
}
}

C# My form objects don't work properly after application running a while

I have 2 pictureboxes and a couple of labels and buttons in my form. The application reads variables from a PLC to draw a graph on pictureboxes and checks if any alarm has been occured by reading variables from PLC. I have 3 timers working at 0.5, 1 and 30 seconds interval for each one. After a while, pictureboxes go invalid. I mean red rectangle on white background by invalid. Buttons don't work. I run application from exe built by debug mode. No errors or exceptions have been occured. Should i refresh my form by my code? Should i enable double buffering property? Or what else should i do? Thanks for your time.
Best regards,
Bee-
Note: Before some changes the app worked around a week. And it was all ok. Changes are: 2 timers added(0.5 and 1 sec interval) and added a picturebox.
Edit: When i go debug mode, i figured out that picturebox.Invalidate() commands doesn't refresh picturebox. After invalidate command, debugger didn't hit paint event method. And also buttons creates form object but can't show it. I think there is something wrong with graphics/rendering. I'm just a beginner and thanks for your help. Codes below:
Reading values to create graph and invalidate pictureboxes:
private void timerCommunication_Tick(object sender, EventArgs e)
{
CurrentActiveShift();
if (Global_Variables.isShiftActiveNow)
{
if (adsClient.IsConnected == false)
adsClient.Connect(801);
string info = adsClient.ReadDeviceInfo().ToString();
float ActData = (float)adsClient.ReadAny(16416, 200, typeof(float));
textBox1.Text = Convert.ToString(ActData);
string[] vs = new string[9];
string[] vs1 = new string[6];
if (DateTime.Now.Hour < 10)
vs[0] = "0" + DateTime.Now.Hour.ToString() + ":";
else
vs[0] = DateTime.Now.Hour.ToString() + ":";
if (DateTime.Now.Minute < 10)
vs[0] += "0" + DateTime.Now.Minute.ToString();
else
vs[0] += DateTime.Now.Minute.ToString();
vs[1] = Convert.ToString(ActData);
vs1[0] = vs[0];
ActData = (float)adsClient.ReadAny(16416, 216, typeof(float));
vs1[1] = Convert.ToString(ActData);
float PrmUpperLimit = Global_Variables.PrmSetValue + Global_Variables.PrmAlarm + Global_Variables.PrmWarning + Global_Variables.PrmMaxMin;
float PrmLowerLimit = Global_Variables.PrmSetValue - Global_Variables.PrmAlarm - Global_Variables.PrmWarning - Global_Variables.PrmMaxMin;
float PrmSet = Global_Variables.PrmSetValue;
float PrmUpperWarning = Global_Variables.PrmSetValue + Global_Variables.PrmWarning;
float PrmLowerWarning = Global_Variables.PrmSetValue - Global_Variables.PrmWarning;
float PrmUpperAlarm = PrmUpperWarning + Global_Variables.PrmAlarm;
float PrmLowerAlarm = PrmLowerWarning - Global_Variables.PrmAlarm;
float OvlUpperLimit = Global_Variables.OvlSetValue + Global_Variables.OvlAlarm + Global_Variables.OvlWarning + Global_Variables.OvlMaxMin;
float OvlSet = Global_Variables.OvlSetValue;
float OvlUpperWarning = Global_Variables.OvlSetValue + Global_Variables.OvlWarning;
float OvlUpperAlarm = OvlUpperWarning + Global_Variables.OvlAlarm;
vs[2] = Convert.ToString(PrmUpperLimit);
vs1[2] = Convert.ToString(OvlUpperLimit);
vs[3] = Convert.ToString(PrmUpperAlarm);
vs1[3] = Convert.ToString(OvlUpperAlarm);
vs[4] = Convert.ToString(PrmUpperWarning);
vs1[4] = Convert.ToString(OvlUpperWarning);
vs[5] = Convert.ToString(PrmSet);
vs1[5] = Convert.ToString(OvlSet);
vs[6] = Convert.ToString(PrmLowerWarning);
vs[7] = Convert.ToString(PrmLowerAlarm);
vs[8] = Convert.ToString(PrmLowerLimit);
//string Header = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString() + "," + TimeSpan.FromMinutes(Global_Variables.CurrentShiftStart).ToString(#"hh\.mm") + "-" + TimeSpan.FromMinutes(Global_Variables.CurrentShiftEnd).ToString(#"hh\.mm");
string Header = DateTime.Now.ToString("yyyy.MM.dd") + "," + TimeSpan.FromMinutes(Global_Variables.CurrentShiftStart).ToString(#"hh\.mm") + "-" + TimeSpan.FromMinutes(Global_Variables.CurrentShiftEnd).ToString(#"hh\.mm");
//string Dir = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString();
string Dir = DateTime.Now.ToString("yyyy.MM.dd");
System.IO.Directory.CreateDirectory(Application.StartupPath + "\\Archive\\" + Dir);
MeasuringLog.WriteLog(Application.StartupPath + "\\Archive\\" + Dir + "\\" + Header + ".txt", vs);
MeasuringLog.WriteLog(Application.StartupPath + "\\Archive\\" + Dir + "\\" + Header + ".txt", vs1);
picboxPerimeter.Invalidate();
picboxOvality.Invalidate();
}
Picturebox Paint Event:
private void picboxPerimeter_Paint(object sender, PaintEventArgs e)
{
CurrentActiveShift();
if (Global_Variables.isShiftActiveNow)
{
string[] X = new string[2];
//string Header = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString() + "," + TimeSpan.FromMinutes(Global_Variables.CurrentShiftStart).ToString(#"hh\.mm") + "-" + TimeSpan.FromMinutes(Global_Variables.CurrentShiftEnd).ToString(#"hh\.mm");
string Header = DateTime.Now.ToString("yyyy.MM.dd") + "," + TimeSpan.FromMinutes(Global_Variables.CurrentShiftStart).ToString(#"hh\.mm") + "-" + TimeSpan.FromMinutes(Global_Variables.CurrentShiftEnd).ToString(#"hh\.mm");
//string Dir = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString();
string Dir = DateTime.Now.ToString("yyyy.MM.dd");
string path = Application.StartupPath + "\\Archive\\" + Dir + "\\" + Header + ".txt";
try
{
int index;
string[] ReadLog = System.IO.File.ReadAllLines(path);
float LargestSet = LargestLimit(ReadLog, 5, 0, out index);
float LargestTrend = LargestLimit(ReadLog, 2, 0, out index);
string[] FillLbL = ReadLog[index].Split('|');
string[] myL = ReadLog[index].Split('|');
FillLabelsPrm(FillLbL);
Trend.SetTrendLimits(LargestTrend, float.Parse(myL[8]));
listPerimeter.Clear();
X[0] = TimeSpan.FromMinutes(Global_Variables.CurrentShiftStart).ToString(#"hh\:mm");
X[1] = TimeSpan.FromMinutes(Global_Variables.CurrentShiftEnd).ToString(#"hh\:mm");
Trend.Time = X;
string[] unravel = ReadLog[0].Split('|');
Trend.p1 = unravel;
for (int i = 2; i <= ReadLog.Length - 1; i += 2)
{
unravel = ReadLog[i].Split('|');
bool Check = Trend.DrawWholePicture(unravel, sender, e, listPerimeter);
}
}
catch
{
;
}
Point L_ptc = new Point();
L_ptc = picboxPerimeter.PointToClient(new Point(0, 0));
L_ptc = new Point(-L_ptc.X, -L_ptc.Y + picboxPerimeter.Size.Height);
Pen p = new Pen(Color.Black, 1.5f);
Label[] labels = new Label[17];
for (int i = 0; i <= 16; i++)
{
e.Graphics.DrawLine(p, i * picboxPerimeter.Width / 16, 0, i * picboxPerimeter.Width / 16, picboxPerimeter.Height);
labels[i] = new Label();
this.Controls.Add(labels[i]);
labels[i].Location = new Point(L_ptc.X - 15 + i * picboxPerimeter.Width / 16, L_ptc.Y - 15);
labels[i].BackColor = Color.Transparent;
labels[i].Size = new Size(35, 15);
labels[i].BringToFront();
try
{
double archive_sh = Convert.ToDouble(X[0].Substring(0, 2)) * 60 + Convert.ToDouble(X[0].Substring(3));
double archive_sh1 = Convert.ToDouble(X[1].Substring(0, 2)) * 60 + Convert.ToDouble(X[1].Substring(3));
if (archive_sh1 < archive_sh)
archive_sh1 += 24 * 60;
double a = archive_sh1 - archive_sh;
a /= 16.00;
double b = archive_sh;
TimeSpan span = TimeSpan.FromMinutes(b + i * a);
labels[i].Text = span.ToString(#"hh\:mm");
}
catch
{
;
}
}
}
}
The other picturebox' event is the same, the difference is: this one draw graph according to odd numbered lines of txt file and the other draws according to even numbered lines. Adding other timers' tick event methods below, don't know if necessary though.
Timer1; 1 sec interval, checks alarm values from PLC:
private void timer1_Tick(object sender, EventArgs e)
{
lblNotification.Text = "";
if (adsClient.IsConnected == false)
adsClient.Connect(801);
if((bool)adsClient.ReadAny(16417, 1, typeof(bool)))
{
adsClient.WriteAny(16417, 1, false);
}
if ((bool)adsClient.ReadAny(16417, 2, typeof(bool)))
{
adsClient.WriteAny(16417, 2, false);
}
bool alarm = (bool)adsClient.ReadAny(16416, 1, typeof(bool));
bool alarm1 = (bool)adsClient.ReadAny(16416, 2, typeof(bool));
bool[] myBool = (bool[])adsClient.ReadAny(16416, 400, typeof(bool[]), new int[] { 14 });
//string alarmDir = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString();
string alarmDir = DateTime.Now.ToString("yyyy.MM.dd");
System.IO.Directory.CreateDirectory(Application.StartupPath + "\\Alarm\\" + alarmDir);
//string alarmPath = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString() + "," + TimeSpan.FromMinutes(Global_Variables.CurrentShiftStart).ToString(#"hh\.mm") + "-" + TimeSpan.FromMinutes(Global_Variables.CurrentShiftEnd).ToString(#"hh\.mm");
string alarmPath = DateTime.Now.ToString("yyyy.MM.dd") + "," + TimeSpan.FromMinutes(Global_Variables.CurrentShiftStart).ToString(#"hh\.mm") + "-" + TimeSpan.FromMinutes(Global_Variables.CurrentShiftEnd).ToString(#"hh\.mm");
int alarmCount = 0;
for (int i=0; i <= myBool.Length - 1; i++)
{
alarmMessage[i] = AlarmLog.GetMessage(i);
if (!alarmisActive[i] && myBool[i])
{
alarmisActive[i] = true;
alarmActiveTime[i] = DateTime.Now.ToString("HH:mm");
alarmCount++;
if (!alarmisWritten[i])
{
lblNotification.Text = alarmMessage[i];
alarmisWritten[i] = true;
alarmFileData = alarmMessage[i] + "|" + alarmActiveTime[i] + "|" + alarmisActive[i].ToString() + "|" + alarmDeactiveTime[i] + "\r\n";
System.IO.File.AppendAllText(Application.StartupPath + "\\Alarm\\" + alarmDir + "\\" + alarmPath + ".txt", alarmFileData);
}
}
else if(alarmisActive[i] && !myBool[i])
{
if (alarmisWritten[i])
{
alarmisActive[i] = false;
alarmDeactiveTime[i] = DateTime.Now.ToString("HH:mm");
alarmisWritten[i] = false;
alarmFileData = alarmMessage[i] + "|" + alarmActiveTime[i] + "|" + alarmisActive[i].ToString() + "|" + alarmDeactiveTime[i] + "\r\n";
System.IO.File.AppendAllText(Application.StartupPath + "\\Alarm\\" + alarmDir + "\\" + alarmPath + ".txt", alarmFileData);
}
}
}
bool etherCatAlarm = (bool)adsClient.ReadAny(16417, 7, typeof(bool));
alarmMessage[14] = AlarmLog.GetMessage(14);
if (!alarmisActive[14] && etherCatAlarm)
{
alarmisActive[14] = true;
alarmActiveTime[14]= DateTime.Now.ToString("HH:mm");
alarmCount++;
if (!alarmisWritten[14])
{
alarmisWritten[14] = true;
alarmFileData = alarmMessage[14]+ "|" + alarmActiveTime[14] + "|" + alarmisActive[14].ToString() + "|" + alarmDeactiveTime[14] + "\r\n";
System.IO.File.AppendAllText(Application.StartupPath + "\\Alarm\\" + alarmDir + "\\" + alarmPath + ".txt", alarmFileData);
}
}
else if (alarmisActive[14] && !etherCatAlarm)
{
if (alarmisWritten[14])
{
alarmisActive[14] = false;
alarmDeactiveTime[14] = DateTime.Now.ToString("HH:mm");
alarmisWritten[14] = false;
alarmFileData = alarmMessage[14] + "|" + alarmActiveTime[14] + "|" + alarmisActive[14].ToString() + "|" + alarmDeactiveTime[14] + "\r\n";
System.IO.File.AppendAllText(Application.StartupPath + "\\Alarm\\" + alarmDir + "\\" + alarmPath + ".txt", alarmFileData);
}
}
if(alarmCount > 1)
{
lblNotification.Text = "Multiple alarms are active, check \"Active Alarm\" page...";
}
else if (alarmCount == 1)
{
for (int i = 0; i <= 13; i++)
{
lblNotification.Text = alarmMessage[i];
}
}
}
Timer2; 0.5 sec interval, reads values to show in labels:
private void timer2_Tick(object sender, EventArgs e)
{
if (adsClient.IsConnected == false)
adsClient.Connect(801);
float[] Actual = (float[])adsClient.ReadAny(16416, 200, typeof(float[]), new int[] { 8 });
lblPerimeterValue.Text = Actual[0].ToString();
lblPerimeterX.Text = Actual[1].ToString();
lblPerimeterY.Text = Actual[2].ToString();
lblOvalityValue.Text = Actual[4].ToString();
lblOvalityX.Text = Actual[5].ToString();
lblOvalityY.Text = Actual[6].ToString();
}

Formula not identify cell values

I'm generating an excel using the following code in my ASP.Net MVC Application
var fileName = DateTime.Now.ToString("yyyy-MM-dd--hh-mm-ss") + ".xlsx";
var outputDir = ConfigurationManager.AppSettings["ExcelUploadPath"];
// var fileName = "ExcellData.xlsx";
var file = new FileInfo(outputDir + fileName);
var fDate = JsonConvert.DeserializeObject<DateTime>(fromDate);
var tDate = JsonConvert.DeserializeObject<DateTime>(toDate);
using (var package = new OfficeOpenXml.ExcelPackage(file))
{
// add a new worksheet to the empty workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Plan " + DateTime.Now.ToShortDateString());
// --------- Data and styling goes here -------------- //
DataTable dt = planService.GetFlow(fDate, tDate, customerId, ordertypeId, suppliers, items);
if (dt != null)
{
int iCol = 1;
// Add column headings...
for (int i = 9; i < dt.Columns.Count; i++)
{
dt.Columns[i].ColumnName = dt.Columns[i].ColumnName.MultiInsert("/", 1, 3);
}
foreach (DataColumn c in dt.Columns)
{
worksheet.Cells[1, iCol].Value = c.ColumnName;
worksheet.Cells[1, iCol].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[1, iCol].Style.Font.Bold = true;
worksheet.Cells[1, iCol].Style.Fill.BackgroundColor.SetColor(Color.LightGray);
iCol++;
}
for (int j = 0; j < dt.Rows.Count; j++)
{
for (int k = 0; k < dt.Columns.Count; k++)
{
worksheet.Cells[j + 2, k + 1].Value = dt.Rows[j].ItemArray[k].ToString();
if (int.Parse(dt.Rows[j].ItemArray[7].ToString()) == 6)
{
worksheet.Cells[j + 2, k + 1].Style.Locked = false;
worksheet.Cells[j + 2, k + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[j + 2, k + 1].Style.Fill.BackgroundColor.SetColor(Color.Cyan);
}
if (int.Parse(dt.Rows[j].ItemArray[7].ToString()) == 7)
{
worksheet.Cells[j + 2, k + 1].Style.Locked = false;
worksheet.Cells[j + 2, k + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[j + 2, k + 1].Style.Fill.BackgroundColor.SetColor(Color.Magenta);
//worksheet.Cells[j + 2, k + 1].Formula =
if((k+1) > 10){
var addressList = new List<string>();
for (int i = 11; i <= k+1; i++)
{
addressList.Add(worksheet.Cells[((j + 2) -1) , i].Address);
}
var lstAdress = String.Join(",", addressList);
worksheet.Cells[j + 2, k + 1].Formula = "SUM(" + lstAdress + ")";
}
}
if (int.Parse(dt.Rows[j].ItemArray[7].ToString()) == 8)
{
//worksheet.Cells[j + 2, k + 1].Style.Locked = false;
worksheet.Cells[j + 2, k + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[j + 2, k + 1].Style.Fill.BackgroundColor.SetColor(Color.Gray);
}
}
var colCount = dt.Columns.Count;
// worksheet.Cells[j+2, 8, j+2, colCount- 1].Style.Numberformat.Format = "0.000";
var range = worksheet.Cells[j + 2, 9, j + 2, colCount - 1];
var r = range.ToString();
var decimalValidation = worksheet.DataValidations.AddDecimalValidation(range.ToString());
decimalValidation.ShowErrorMessage = true;
decimalValidation.ErrorStyle = ExcelDataValidationWarningStyle.stop;
decimalValidation.ErrorTitle = "The value you entered is not valid";
decimalValidation.Error = "This cell must be a valid positive number.";
decimalValidation.Operator = ExcelDataValidationOperator.greaterThanOrEqual;
decimalValidation.Formula.Value = 0D;
}
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
worksheet.Column(1).Hidden = true;
worksheet.Column(2).Hidden = true;
worksheet.Column(3).Hidden = true;
worksheet.Column(4).Hidden = true;
worksheet.Column(5).Hidden = true;
worksheet.Column(8).Hidden = true;
worksheet.Column(9).Hidden = true;
worksheet.Column(10).Hidden = true;
worksheet.Protection.IsProtected = true;
// save our new workbook and we are done!
worksheet.Calculate();
package.Save();
return Json(fileName, JsonRequestBehavior.AllowGet);
}
else
{
return Json("NoData", JsonRequestBehavior.AllowGet);
}
}
return Json("", JsonRequestBehavior.AllowGet);
Here I'm setting my formula with comma separated cell names eg:
SUM(A1,A2,A3.. etc)
The excel file is generating correctly. But the problem is the formula calculation is not happen when I open my excel file.
The formula works when I manually change a cell value in Column Type Agreed Flow.
And it can only identify values of manually edited cells.
How can I resolve this?
Formula recalculation is both an Excel and a workbook setting.
You could set it with at the workbook level with
workbook.CalcMode = ExcelCalcMode.Automatic;
If the user has set it to manual though, the formulas won't be recalculated.
If you want to ensure the saved values are correct you can force the calculation by calling
worksheet.Calculate();
You can also calculate the formulas at the workbook or range level, eg :
worksheet.Cells[j + 2, k + 1].Calculate();
or
package.Workbook.Calculate();
This is explained in the documentation. Keep in mind that EPPlus doesn't contain Excel's formula engine. It uses its own engine to parse and calculate formulas. Some things aren't supported
It worked when I change my formula as follows..
var addressList = new List<string>();
for (int i = 11; i <= k+1; i++)
{
addressList.Add(worksheet.Cells[((j + 2) -1) , i].Address);
}
var lstAdress = String.Join("+", addressList);
worksheet.Cells[j + 2, k + 1].Formula = "(" + lstAdress + ")";
I think there is an issue in my excel sheet when I use the SUM function So I write the formula without using it. Then it worked
(A1+B1+C1+D1+ ..... etc)

Testing all cells in datagridview

for (int i = 0; i < metroGrid1.Rows.Count; i++)
{
if (metroGrid1.Rows[i].Cells[0].Value.ToString() == radGridView1.SelectedRows[0].Cells[0].Value.ToString())
{
counter = i;
metroGrid1.Rows[counter].Cells[2].Value = Convert.ToInt32(metroGrid1.Rows[counter].Cells[2].Value) + radSpinEditor1.Value;
MessageBox.Show("for loop");
}
else
{
metroGrid1.Rows.Add(radGridView1.SelectedRows[0].Cells[0].Value.ToString(), radGridView1.SelectedRows[0].Cells[1].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[2].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[3].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[4].Value.ToString(), radSpinEditor1.Value, decimal.Round(prodamt, 2), decimal.Round(prodtotamt, 2));
totamt += prodtotamt;
metroLabelTotalamt.Text = (string.Format("{0:#,###0.00}", totamt));
radSpinEditor1.Value = 1;
MessageBox.Show("else ");
}
}
Shouldn't that be? Since you yourself adding rows to your gridview by calling Add() method as can be seen in your posted code
metroGrid1.Rows.Add(radGridView1.SelectedRows[0].Cells[0].Value.ToString(),
No idea since I don't know your requirement but to me it feels like you wanted to have the other part as else block.
for (int i = 0; i < metroGrid1.Rows.Count; i++)
{
if (metroGrid1.Rows[i].Cells[0].Value.ToString() == radGridView1.SelectedRows[0].Cells[0].Value.ToString())
{
counter = i;
metroGrid1.Rows[counter].Cells[2].Value = Convert.ToInt32(metroGrid1.Rows[counter].Cells[2].Value) + radSpinEditor1.Value;
MessageBox.Show("for loop");
}
else
{
metroGrid1.Rows.Add(radGridView1.SelectedRows[0].Cells[0].Value.ToString(), radGridView1.SelectedRows[0].Cells[1].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[2].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[3].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[4].Value.ToString(), radSpinEditor1.Value, decimal.Round(prodamt, 2), decimal.Round(prodtotamt, 2));
totamt += prodtotamt;
metroLabelTotalamt.Text = (string.Format("{0:#,###0.00}", totamt));
radSpinEditor1.Value = 1;
MessageBox.Show("else ");
}
}

WrapText for column in Excel programmatically

I'm trying to set WrapText property to true with C#.
Range rng = sheet.get_Range("A:A", System.Type.Missing);
rng.EntireColumn.ColumnWidth = 50;
rng.EntireColumn.AutoFit();
rng.EntireRow.AutoFit();
rng.WrapText = true;
but it doesn't work without any exceptions. What's wrong? Thank you!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.IO;
//Initial Declarations//
Excel.Workbook destinationXlWorkBook;
Excel.Worksheet destinationXlWorkSheet;
Excel.Application destinationXlApp;
object misValue = System.Reflection.Missing.Value;
//Launch Excel App//
destinationXlApp = new Excel.Application();
//Load WorkBook in the opened Excel App//
destinationXlWorkBook = destinationXlApp.Workbooks.Add(misValue);
//Load worksheet-1 in the workbook//
destinationXlWorkSheet =
(Excel.Worksheet)destinationXlWorkBook.Worksheets.get_Item(1);
//Set Text-Wrap for all rows true//
destinationXlWorkSheet.Rows.WrapText = true;
//Or, set it for specific rows//
destinationXlWorkSheet.Rows[3].WrapText = true;
destinationXlWorkSheet.Rows[5].WrapText = true;
//Edit individual cells//
xlWorkSheet.Cells[1, 1] = "ID";
xlWorkSheet.Cells[1, 2] = "Name";
xlWorkSheet.Cells[2, 1] = "1";
xlWorkSheet.Cells[2, 2] = "One";
xlWorkSheet.Cells[3, 1] = "2";
xlWorkSheet.Cells[3, 2] = "Two";
//Save and close the Excel//
destinationXlWorkBook.SaveAs("C:\\Users\\UtkarshSinha\\Documents\\SAP\\text.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
//Start quitting and closing Excel//
destinationXlWorkBook.Close(true, misValue, misValue);
destinationXlApp.Quit();
Marshal.ReleaseComObject(destinationXlWorkSheet);
Marshal.ReleaseComObject(destinationXlWorkBook);
Marshal.ReleaseComObject(destinationXlApp);
I am duping A LOT of code here, for my entire solution, TextWrap being one of it. I figure it might come in handy to someone someday.
MAIN PROGRAM:
public int counter;
public void ExportPartsToExcelButton(object sender, RoutedEventArgs e)
{
Type officeType = Type.GetTypeFromProgID("Excel.Application");
if (officeType != null)
{
if (CurrentID != 0)
{
counter = 1;
GeneratePartsXLSX();
}
else
{
MessageBoxEx.Show(this, "No address selected!", "Warning!", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
else
{
MessageBoxEx.Show(this, "Install Microsoft Excel!", "Warning!", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
public void GeneratePartsXLSX()
{
Mouse.OverrideCursor = Cursors.Wait;
string filename = GlobalStrings.building_house_address;
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\";
filename = filename.Replace("/", "+");
if (!File.Exists(path + filename + ".xlsx"))
{
DataGridParts.ExportPartsToExcel(path + filename + ".xlsx"); //You have to include the ".xlsx" extension, otherwise the Office interop detects a possible dot (.) in the file name as an extension. Example: road.block instead of road.block.xlsx
MessageBoxEx.Show(this, "Saved to Desktop");
}
else
{
if (!File.Exists(path + "\\" + filename + " (" + (counter) + ")" + ".xlsx"))
{
DataGridParts.ExportPartsToExcel(path + filename + " (" + (counter) + ")" + ".xlsx");
MessageBoxEx.Show(this, "Saved to Desktop");
}
else
{
counter++;
GeneratePartsXLSX();
}
}
Mouse.OverrideCursor = null;
}
CLASS:
using Microsoft.Office.Interop.Excel;
using System;
using System.Runtime.InteropServices;
namespace SAVETOEXCELPROGRAM
{
public static class ExportToExcel
{
public static void ExportPartsToExcel(this System.Data.DataTable DataTable, string ExcelFilePath = null)
{
int ColumnsCount;
int RowShift = 7;
ColumnsCount = DataTable.Columns.Count;
// load excel, and create a new workbook
Application Excel = new Application();
Excel.Workbooks.Add();
// single worksheet
_Worksheet Worksheet = Excel.ActiveSheet;
Excel.Sheets[1].Name = "WHATEVER";
Worksheet.Columns.NumberFormat = "#"; //Force the "Text" format, so that 1/2 won't get converted to 1st of February for example
Worksheet.Columns.HorizontalAlignment = XlHAlign.xlHAlignLeft; //Text aligment
Worksheet.Columns.VerticalAlignment = XlHAlign.xlHAlignCenter; //Text aligment
object[,] Title = new object[5, 1]; //Array range starts at [1,1], the content index starts at [0,0]
if (GlobalStrings.building_alterantive_addresses.Length == 0)
{
if (GlobalStrings.building_postcode.Length != 0)
{
Title[0, 0] = "DATE: " + DateTime.Now.ToString("dd.MM.yyyy - HH:mm");
Title[2, 0] = "ADDRESS: " + GlobalStrings.building_house_street + " " + GlobalStrings.building_house_number + GlobalStrings.building_house_id + ", " + GlobalStrings.building_postcode + " " + GlobalStrings.building_area;
Title[3, 0] = "C.C.: " + GlobalStrings.building_cadastral_community + ", BUILDING NO.: " + GlobalStrings.building_building_number + ", PLOT NO.: " + GlobalStrings.building_plot_number;
}
else
{
Title[0, 0] = "DATE: " + DateTime.Now.ToString("dd.MM.yyyy - HH:mm");
Title[2, 0] = "ADDRESS: " + GlobalStrings.building_house_street + " " + GlobalStrings.building_house_number + GlobalStrings.building_house_id;
Title[3, 0] = "C.C.: " + GlobalStrings.building_cadastral_community + ", BUILDING NO.: " + GlobalStrings.building_building_number + ", " + GlobalStrings.building_plot_number;
}
}
else
{
if (GlobalStrings.building_postcode.Length != 0)
{
Title[0, 0] = "DATE: " + DateTime.Now.ToString("dd.MM.yyyy - HH:mm");
Title[2, 0] = "ADDRESS: " + GlobalStrings.building_house_street + " " + GlobalStrings.building_house_number + GlobalStrings.building_house_id + ", " + GlobalStrings.building_postcode + " " + GlobalStrings.building_area;
Title[3, 0] = "C.C.: " + GlobalStrings.building_cadastral_community + ", BUILDING NO.: " + GlobalStrings.building_building_number + ", PLOT NO.: " + GlobalStrings.building_plot_number;
Title[4, 0] = "LOOK ALSO: " + GlobalStrings.building_alterantive_addresses;
}
else
{
Title[0, 0] = "DATE: " + DateTime.Now.ToString("dd.MM.yyyy - HH:mm");
Title[2, 0] = "ADDRESS: " + GlobalStrings.building_house_street + " " + GlobalStrings.building_house_number + GlobalStrings.building_house_id;
Title[3, 0] = "C.C.: " + GlobalStrings.building_cadastral_community + ", BUILDING NO.: " + GlobalStrings.building_building_number + ", PLOT NO.: " + GlobalStrings.building_plot_number;
Title[4, 0] = "LOOK ALSO: " + GlobalStrings.building_alterantive_addresses;
}
}
Range TitleRange = Worksheet.get_Range((Range)(Worksheet.Cells[5, 1]), (Range)(Worksheet.Cells[1, 1]));
TitleRange.Value = Title;
TitleRange.Font.Bold = true;
TitleRange.Font.Size = 10;
object[] Header = new object[14]; //Number of Headers
Header[0] = "PART";
Header[1] = "SHARE";
Header[2] = "CRP";
Header[3] = "+/-";
Header[4] = "OWNER";
Header[5] = "ADDRESS";
Header[6] = "POSTCODE";
Header[7] = "AREA";
Header[8] = "COUNTRY";
Header[9] = "SOCIAL";
Header[10] = "TYPE";
Header[11] = "DESCRIPTION";
Header[12] = "COMMENT";
Header[13] = "CODE";
int MaxCol = Header.Length;
Range HeaderRange = Worksheet.get_Range((Range)(Worksheet.Cells[RowShift, 2]), (Range)(Worksheet.Cells[RowShift, MaxCol + 1])); //MaxCol+1, because we have to shift the Array position by 1, as the first column is set to "ColumnWidth = 0.1"
HeaderRange.Value = Header;
HeaderRange.Font.Bold = true;
HeaderRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGray);
HeaderRange.Borders.LineStyle = XlLineStyle.xlContinuous;
// DataCells
int RowsCount = DataTable.Rows.Count;
object[,] Cells = new object[RowsCount, ColumnsCount]; //Array range starts at [1,1], the content index starts at [0,0]
for (int j = 0; j < RowsCount; j++)
{
for (int i = 3; i <= ColumnsCount - 2; i++) //With this you control the data range, starts with 0, you can exclude data with an " if (i != 0 && i != 1 && ... && i= 5)
{
Cells[j, i - 3] = DataTable.Rows[j][i]; //with i you control the horizontal placement of the data in the worksheet
}
}
Range CellRange = Worksheet.get_Range((Range)(Worksheet.Cells[RowShift + 1, 2]), (Range)(Worksheet.Cells[RowShift + RowsCount, MaxCol + 1])); //MaxCol+1, because we have to shift the Array position by 1, as the first column is set to "ColumnWidth = 0.1"
CellRange.Value = Cells;
CellRange.Borders.LineStyle = XlLineStyle.xlContinuous;
Worksheet.Columns[1].ColumnWidth = 0.1; //If this was set on AutoFit the Column 1 would get extended to the Title Width, because they share the column.
Worksheet.Columns[2].ColumnWidth = 3;
Worksheet.Columns[3].ColumnWidth = 4;
Worksheet.Columns[4].ColumnWidth = 3;
Worksheet.Columns[5].ColumnWidth = 2;
Worksheet.Columns[6].ColumnWidth = 13;
Worksheet.Columns[7].ColumnWidth = 15;
Worksheet.Columns[8].ColumnWidth = 4;
Worksheet.Columns[9].ColumnWidth = 8;
Worksheet.Columns[10].ColumnWidth = 6;
Worksheet.Columns[11].ColumnWidth = 10;
Worksheet.Columns[12].ColumnWidth = 18;
Worksheet.Columns[13].ColumnWidth = 16;
Worksheet.Columns[14].ColumnWidth = 18;
Worksheet.Columns[MaxCol + 1].ColumnWidth = 15; //Set the Width of the last Column
for (int b = 2; b <= MaxCol; b++) //If we wanted to include the "Header[14]", we would have to set MaxCol+1, because the Array (not the DataTable) is shifted by +1. These are Excel Worksheet settings!
{
Worksheet.Columns[b].WrapText = true;
//Worksheet.Columns[b].AutoFit();
}
for (int b = 2; b <= MaxCol + 1; b++)
{
Worksheet.Columns[b].Font.Size = 7;
}
Worksheet.PageSetup.Orientation = XlPageOrientation.xlLandscape;
Worksheet.PageSetup.TopMargin = 0.5;
Worksheet.PageSetup.BottomMargin = 0.5;
Worksheet.PageSetup.RightMargin = 0.5;
Worksheet.PageSetup.LeftMargin = 0.5;
// check fielpath
if (ExcelFilePath != null && ExcelFilePath != "")
{
Worksheet.SaveAs(ExcelFilePath);
Excel.Quit();
Marshal.FinalReleaseComObject(Worksheet);
Marshal.FinalReleaseComObject(TitleRange);
Marshal.FinalReleaseComObject(HeaderRange);
Marshal.FinalReleaseComObject(CellRange);
Marshal.FinalReleaseComObject(Excel);
}
else
// no filepath is given
{
Excel.Visible = true;
}
}
}
}
workSheet.Cells["A1:T1"].Style.WrapText = true;

Categories

Resources