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)
Related
I want to merge rows in my exported excel using epplus. This code below only works if I just have one same value in one column.
e.g (I merge same value in Col1 row) :
But, if I have another table like this, the code getting error while do merge (I merge same value in Col1 and Col2 row)
Pls, help me fix the code.
void mergeCells(DataTable dt, int startIndex, int totalColumns, ExcelWorksheet ws)
{
if (totalColumns == 0) return;
int i, count = 1;
ArrayList lst = new ArrayList();
lst.Add(ws.Cells[2, 1]);
var ctrl = ws.Cells[startIndex + 1, 1];
for (i = 1; i <= dt.Rows.Count; i++)
{
ExcelRange nextMerge = ws.Cells[i + totalColumns + 1, 1];
if (ctrl.Text == nextMerge.Text)
{
count++;
lst.Add(ws.Cells[i, 1]);
}
else
{
if (count > 1)
{
ws.Cells[i + 1, 1, i + count, 1].Merge = true;
mergeCells(new DataTable(lst.ToString()), startIndex + count, totalColumns, ws);
}
count = 1;
lst.Clear();
ctrl = ws.Cells[i + 2, startIndex];
lst.Add(ws.Cells[i, 1]);
}
}
if (count > 1)
{
ws.Cells[startIndex + 1, 1, startIndex + count, 1].Merge = true;
mergeCells(new DataTable(lst.ToString()), startIndex + count, totalColumns - 1, ws);
}
count = 1;
lst.Clear();
}
I have done like this:
public void WriteDataToSheet(DataTable data)
{
using (ExcelPackage excel = new ExcelPackage())
{
ExcelWorksheet ws = excel.Workbook.Worksheets.Add("Test");
ws.Cells["A1"].LoadFromDataTable(data, true);
ws.Cells[ws.Dimension.Address].AutoFitColumns();
var listObject = data.AsEnumerable()
.Select(x => new
{
Col1 = x.Field<string>("Col1"),
Col2 = x.Field<string>("Col2"),
Col3 = x.Field<string>("Col3")
}).ToList();
var lisa = listObject.GroupBy(x => x.Col1).
Select(x => new
{
Id = x.Key,
Quantity = x.Count(),
secondGroup = x.GroupBy(y => y.Col2)
.Select(y => new
{
ID = y.Key,
secondGroup = y.Count()
})
});
int A = 1, B = 0, C = 1, D = 0;
foreach (var item in lisa)
{
B = A + 1;
A += item.Quantity;
ws.Cells["A" + B + ":A" + A + ""].Merge = true;
ws.Cells["B" + B + ":B" + A + ""].Merge = true;
foreach (var item2 in item.secondGroup)
{
D = C + 1;
C += item2.secondGroup;
ws.Cells["C" + D + ":C" + C + ""].Merge = true;
}
}
// Save merged and modified file to the location
}
}
I have a set of codes to export grid view data to excel using EPPLUS. I am able to export the data to EPPLUS. But how do I export the colour of the font to excel as well? Can I set the dynamic coding for the font colour if ..... colour = green if ..... colour = red?
Thus I will need column4 to be coloured as well according to the value I set.
The below codes is how I set dynamically for gridview:
if (e.Row.RowType == DataControlRowType.DataRow)
{
TableCell cell = e.Row.Cells[16];
int Num = int.Parse(cell.Text);
if (Num >= 1&& Num <= 11)
{
cell.ForeColor = Color.Green;
}
if (Num >= 12&& Num <= 39)
{
cell.ForeColor = Color.Orange;
}
..........
}
The codes for my export:
protected void EXPORT_BUTTON_Click(object sender, EventArgs e)
{
ExcelPackage package = new ExcelPackage();
ExcelWorksheet Grid = package.Workbook.Worksheets.Add("ORSA ASSESSMENTS");
DataTable Gridview1 = new DataTable();
for (int i = 0; i < Gridview1.Columns.Count; i++)
{
Gridview1.Columns.Add("column" + i.ToString());
}
foreach (GridViewRow row in Gridview1.Rows)
{
DataRow dr = Gridview1.NewRow();
for (int j = 0; j < Gridview1.Columns.Count; j++)
{
row.Cells[j].Text = row.Cells[j].Text.Replace(" ", " ");
dr["column" + j.ToString()] = row.Cells[j].Text;
}
Gridview1.Rows.Add(dr);
}
Grid.Cells["A1"].LoadFromDataTable(Gridview1, true);
using (ExcelRange rng = Grid.Cells["A1:Z1"])
{
rng.Style.Font.Bold = true;
}
Grid.Cells[ORSA.Dimension.Address].AutoFitColumns();
var FolderPath = ServerName + DirectoryLocation + DirectoryFolder + ExportsFolder;
var filename = ExcelName + #"_" + ".xlsx";
var filepath = new FileInfo(Path.Combine(FolderPath, filename));
Response.Clear();
package.SaveAs(filepath);
Response.AddHeader("content-disposition", "attachment; filename=" + filename + ";");
Response.Charset = "";
Response.ContentType = "application/vnd.xlsx";
Response.TransmitFile(filepath.FullName);
Response.End();
}
Thus how can I do in my export codes so that I can export or set the forecolour dynamically upon exporting?
thanks
After this line
Grid.Cells["A1"].LoadFromDataTable(Gridview1, true);
Do a looping to loop the count of your DataTable
Example
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
DataTable dt = new DataTable();
// Create Column
for(int i = 0; i < 5; i++)
dt.Columns.Add("column" + i, typeof(int));
for (int i = 0; i < 10; i++)
dt.Rows.Add(i, i+1, i+2, i+3, i+4);
GenerateExcel(dt);
}
}
private void GenerateExcel(DataTable dt)
{
using (ExcelPackage pkg = new ExcelPackage())
{
ExcelWorksheet ws = pkg.Workbook.Worksheets.Add("Sheet1");
int num = 0;
string value = string.Empty;
ws.Cells[1, 1].LoadFromDataTable(dt, true);
// Get Your DataTable Count
int count = dt.Rows.Count;
int countCol = dt.Columns.Count;
bool isHeader = true;
for (int i = 0; i < count; i++ )
{
// Set Border
for (int j = 1; j <= countCol; j++)
{
// Set Border For Header. Run once only
if (isHeader) ws.Cells[1, j].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin, System.Drawing.Color.Black);
ws.Cells[2 + i, j].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin, System.Drawing.Color.Black);
}
// Set to false
isHeader = false;
// Cells 2 + i == Rows, Wondering start with 2 because your 1st rows is Title so 2 is the value
// Cells 2 == Column make sure your column is fix
value = ws.Cells[2 + i, 2].Value + ""; // You can use .ToString() if u sure is not null
// Parse
int.TryParse(value, out num);
// Check
if (num >= 1 && num <= 11)
ws.Cells[2 + i, 2].Style.Font.Color.SetColor(System.Drawing.Color.Green);
else if (num >= 12 && num <= 39)
ws.Cells[2 + i, 2].Style.Font.Color.SetColor(System.Drawing.Color.Orange);
}
pkg.SaveAs(new FileInfo("C:\\Test.xlsx"));
}
}
I am working on some code that a developer I replaced wrote. He wrote a lengthy piece of code what writes to multiple excel worksheets on the same excel file. I am thinking about using several background workers to speed up the process of writing to four excel worksheets. Would there be a reason why it would be a good idea to leave all this on one thread? I have used multi-threading before, but not in c# and not writing to excel. I could not find any documentation either way.
Here is the code
xlWorkSheet = xlWorkBook.Worksheets.get_Item(1);
// work order
xlWorkSheet.Cells[4, 4] = nld.s_WorkOrderNumber;
// technician
xlWorkSheet.Cells[6, 4] = nld.s_TechnicianName;
// date and time
xlWorkSheet.Cells[4, 10] = (string)DateTime.Now.ToShortDateString();
xlWorkSheet.Cells[6, 10] = (string)DateTime.Now.ToShortTimeString();
row = 30;
col = 1;
// left connectors and part number
conCount = nld.n_LeftConnCount;
for (i = 0; i < conCount; i++)
{
xlWorkSheet.Cells[row, col] = "Name: " + nld.ConnDataLeft[i].s_ConnName + " PartNo: " + nld.ConnDataLeft[i].s_ConnPartNumber;
row++;
}
// Right connectors and part number
row = 30;
col = 7;
conCount = nld.n_RightConnCount;
for (i = 0; i < conCount; i++)
{
xlWorkSheet.Cells[row, col] = "Name: " + nld.ConnDataRight[i].s_ConnName + " PartNo: " + nld.ConnDataRight[i].s_ConnPartNumber;
row++;
}
// put down the pin map onNetlist worksheet
xlWorkSheet = xlWorkBook.Worksheets.get_Item(2);
row = 5;
col = 1;
i = 0;
leftPinNum = 0;
int connCount = nld.pinMap.Count;
for(i = 0; i < connCount; i++)
{
xlWorkSheet.Cells[row, col] = (i+1).ToString();
leftPinNum = nld.pinMap[i].pinLeft;
xlWorkSheet.Cells[row, col + 1] = nld.pinMap[i].conLeftName;
xlWorkSheet.Cells[row, col + 2] = nld.pinMap[i].pinLeftName;
xlWorkSheet.Cells[row, col + 4] = nld.pinMap[i].conRightName;
xlWorkSheet.Cells[row, col + 5] = nld.pinMap[i].pinRightName;
row++;
}
// put down the pin map onNetlist worksheet
xlWorkSheet = xlWorkBook.Worksheets.get_Item(3);
row = 5;
col = 1;
i = 0;
leftPinNum = 0;
for (i = 0; i < connCount; i++)
{
xlWorkSheet.Cells[row, col] = (i + 1).ToString();
leftPinNum = nld.pinMap[i].pinLeft;
xlWorkSheet.Cells[row, col + 1] = nld.pinMap[i].conLeftName;
xlWorkSheet.Cells[row, col + 2] = nld.pinMap[i].pinLeftName;
xlWorkSheet.Cells[row, col + 4] = nld.pinMap[i].conRightName;
xlWorkSheet.Cells[row, col + 5] = nld.pinMap[i].pinRightName;
if (facadeIntoNetList.ReturnIfUseShort(i))
{
xlWorkSheet.Cells[row, col + 7] = "True";
}
else
{
xlWorkSheet.Cells[row, col + 9] = "True";
}
row++;
}
// put down the pin map onNetlist worksheet
xlWorkSheet = xlWorkBook.Worksheets.get_Item(4);
row = 5;
col = 1;
i = 0;
leftPinNum = 0;
for (i = 0; i < connCount; i++)
{
xlWorkSheet.Cells[row, col] = (i + 1).ToString();
leftPinNum = nld.pinMap[i].pinLeft;
xlWorkSheet.Cells[row, col + 1] = nld.pinMap[i].conLeftName;
xlWorkSheet.Cells[row, col + 2] = nld.pinMap[i].pinLeftName;
xlWorkSheet.Cells[row, col + 6] = nld.pinMap[i].conRightName;
xlWorkSheet.Cells[row, col + 7] = nld.pinMap[i].pinRightName;
row++;
}
I know the temptation to do this: Those Office COM interfaces are painfully slow. But they also don't support multithreading at all. It's not a C# issue, it is an Excel+COM issue. If you need speed, then write an .xlsx using a 3rd-party library then launch Excel to open the file. That might literally be hundreds of times faster.
I'm building a report in which try to copy the previous row cell styles in the following
for (int i = 0; i < DataSource.Length; i++)
{
int rowNumber = i + s;
Excel.Range RngToCopy = ObjWorkSheet.get_Range("A" + rowNumber.ToString(), "K" + rowNumber.ToString());
Excel.Range r = ObjWorkSheet.get_Range("A" + (rowNumber + 1).ToString(), "K" + (rowNumber + 1).ToString());
RngToCopy.Copy(Type.Missing);
r.Insert(Excel.XlInsertShiftDirection.xlShiftDown);
r.PasteSpecial(Excel.XlPasteType.xlPasteFormats,
Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);
ObjWorkSheet.Cells[rowNumber, 1] = i + 1;
ObjWorkSheet.Cells[rowNumber, 2] = DataSource[i].TerminalName;
ObjWorkSheet.Cells[rowNumber, 3] = DataSource[i].Type;
ObjWorkSheet.Cells[rowNumber, 4] = DataSource[i].Requisite;
}
everything works but very long
How can I speed this up?
I think you manually copy you will be improved.
Object[] origData = origRange.Value2;
destRange.Value2 = origData;
That should be WAY faster.
I'm having some trouble reading from an Excel spreadsheet in C#.
I have this code which I read every cell from A to X.
System.Array myvalues; string[] strArray;
Microsoft.Office.Interop.Excel.Range range =
worksheet.get_Range("A" + i.ToString(), "W" + i.ToString());
while(range.Count!=0)
{
i++;
//Console.WriteLine(i);
range = worksheet.get_Range("A" + i.ToString(), "W" + i.ToString());
myvalues = (System.Array)range.Cells.Value;
strArray = ConvertToStringArray(myvalues);
name = clearstr(strArray[1]);
for ( int j = 1 ; j <= Int32.Parse(number_add_file)*4 ; j++)
{
name = "";
lang_add = "";
price = "";
description = "";
Console.WriteLine("I got in!");
Microsoft.Office.Interop.Excel.Range range_add =
worksheet.get_Range("X" + i.ToString(),Type.Missing);
System.Array values = (System.Array)range_add.Cells.Value;
string[] str = ConvertToStringArray(values);
name = str[0];
lang_add = str[1];
price = str[2];
description = str[3];
Console.WriteLine(name + " "
+ lang_add + " " + price + " " + description);
addfile();
}
My question is: How could i read next 4 * "number" rows in excel based on "number" value ?
For example:
A B C D E F G H I J
a a a a a 1 a a a a
F's cell value is 1 so I would like to read ( G H I J)
If F's cell value is 2 the I would like to read ( G H I J K L M N)
A B C D E F G H I J K L M N
a a a a a 2 a a a a a a a a
F's cell value 3 :
A B C D E F G H I J K L M N O P Q R
a a a a a 3 a a a a a a a a a a a a
This is for .NET 4.0:
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open("somefile.xls");
Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[1]; // assume it is the first sheet
Excel.Range xlRange = xlWorksheet.UsedRange; // get the entire used range
int value = 0;
if(Int32.TryParse(xlRange.Cells[1,6].Value2.ToString(), out value)) // get the F cell from the first row
{
int numberOfColumnsToRead = value * 4;
for(int col=7; col < (numberOfColumnsToRead + 7); col++)
{
Console.WriteLine(xlRange.Cells[1,col].Value2.ToString()); // do whatever with value
}
}
This will open the workbook and get the first worksheet in the workbook. We then get the entire used range and put that in the range variable. From there, we try to parse the int in column "F" (which is the 6th column, it is 1 based not zero based) in the first row. If that parsing is successful, we then multiply that number by 4 to see how many columns you need (in your post you said rows, but your examples were columns). We use a for loop to start at the G column (column 7) and go to the number of columns to read + 7 (to account for the columns that we skipped). You would be free to do what you want with the values but for this example I just wrote them to the console.
It is inot direct answer to your question, but you can easily refer to your cells like this:
int row1 = 1;
int row2 = 5;
sheet1.Cells[row1, row1+row2].Value=row1.ToString();
String Rng = Convert.ToString(sheet1.Cells[row1, row2-row1].Address());
string testList = "";
String str1 = "";
string logPath = #"E:\LogForConsoleApp.txt";
string filePath = #"E:\SaveSheetName.txt";
string Path = #"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\MSTest";
List<string> ltSheetName = new List<string>();
List<string> ltMethodName = new List<string>();
Process myProcess = new Process();
Excel.Application appExl = new Excel.Application();
Excel.Workbook workbook = null;
Excel.Worksheet NwSheet;
Excel.Range ShtRange;
appExl = new Excel.Application();
workbook = appExl.Workbooks.Open("E:\\inputSheet3", Missing.Value, ReadOnly: false);
NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);
ShtRange = NwSheet.UsedRange; //gives the used cells in sheet
int rCnt = 0;
int cCnt = 0;
for (rCnt = 1; rCnt <= ShtRange.Rows.Count; rCnt++)
{
for (cCnt = 1; cCnt <= ShtRange.Columns.Count; cCnt++)
{
if (Convert.ToString(NwSheet.Cells[rCnt, cCnt].Value2) == "Y")
{
ltSheetName.Add(NwSheet.Cells[rCnt, cCnt - 1].Value2);
//ltMethodName.Add(" /test:" + NwSheet.Cells[rCnt, cCnt - 1].Value2);
}
}
}
workbook.Close(false, Missing.Value, Missing.Value);
appExl.Quit();
for (int sht = 0; sht < ltSheetName.Count; sht++)
{
ltMethodName.Clear();
appExl = new Excel.Application();
workbook = appExl.Workbooks.Open(ltSheetName[sht].ToString(), Missing.Value, ReadOnly: false);
NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);
ShtRange = NwSheet.UsedRange; //gives the used cells in sheet
int rCnt1 = 0;
int cCnt1 = 0;
for (rCnt1 = 1; rCnt1 <= ShtRange.Rows.Count; rCnt1++)
{
for (cCnt1 = 1; cCnt1 <= ShtRange.Columns.Count; cCnt1++)
{
if (Convert.ToString(NwSheet.Cells[rCnt1, cCnt1].Value2) == "Y")
{
ltMethodName.Add(" /test:" + NwSheet.Cells[rCnt, cCnt - 1].Value2);
}
}
}
workbook.Close(false, Missing.Value, Missing.Value);
appExl.Quit();
for (int i = 0; i < ltMethodName.Count; i++)
{
str1 = ltMethodName[i].ToString();
testList += str1;
}
string foldername = "TestResult_" + DateTime.Today.ToString().Remove(DateTime.Today.ToString().LastIndexOf("/") + 5);
foldername = foldername.Replace("/", "");
string direc = #"E:\" + foldername;
string fileName = ltSheetName[sht].ToString().Substring(ltSheetName[sht].ToString().LastIndexOf("\\") + 1) + "_InderdeepAutRes.trx";
if (!Directory.Exists(direc))
Directory.CreateDirectory(direc);
string testcase = "";
if (!File.Exists(direc + "\\" + fileName))
testcase = " /testcontainer:" + "E:\\Practice\\TestingSample\\TestingSample\\bin\\Debug\\TestingSample.dll" + testList + " /resultsfile:" + direc + "\\" + fileName;
else
{
Directory.Delete(direc, true);
Directory.CreateDirectory(direc);
testcase = " /testcontainer:" + "E:\\Practice\\TestingSample\\TestingSample\\bin\\Debug\\TestingSample.dll" + testList + " /resultsfile:" + direc + "\\" + fileName;
}
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(Path, testcase);
try
{
TextWriter tw = new StreamWriter(filePath, false);
tw.WriteLine(ltSheetName[sht].ToString());
tw.Close();
myProcess.StartInfo = myProcessStartInfo;
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;
myProcess.Start();
string output = myProcess.StandardOutput.ReadToEnd();
//myProcess.WaitForExit();
Console.WriteLine(output);
}
catch (Exception ex)
{
TextWriter tw = new StreamWriter(logPath, true);
tw.WriteLine(ex.StackTrace);
tw.Close();
}
}