Read data from Excel files - c#

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();
}
}

Related

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)

Copying single cell value from one Excel document to another Excel document using C#

Im making an app that will use one Excel document that is generated, and place some values from that document to another Excel document, and Im stuck in phase where I need to copy value.
My code:
private void buttonIzvrsi_Click(object sender, EventArgs e)
{
if(textBoxPolazna.Text!="" && textBoxKrajnja.Text != "")
{
Microsoft.Office.Interop.Excel.Application polazniExcel = new Microsoft.Office.Interop.Excel.Application();
polazniExcel.FileValidation = MsoFileValidationMode.msoFileValidationSkip;
Microsoft.Office.Interop.Excel.Workbook polazna = polazniExcel.Workbooks.Open(textBoxPolazna.Text.ToString());
Excel.Worksheet Polazni = polazniExcel.Sheets[1];//sheet koji treba unijeti
Microsoft.Office.Interop.Excel.Application krajnjiExcel = new Microsoft.Office.Interop.Excel.Application();
krajnjiExcel.FileValidation = MsoFileValidationMode.msoFileValidationSkip;
Microsoft.Office.Interop.Excel.Workbook krajnja = krajnjiExcel.Workbooks.Open(textBoxKrajnja.Text.ToString());
Excel.Worksheet Krajnji_PoMT = krajnjiExcel.Sheets["Po mjestu troška"];//sheet po mjestu troska
Excel.Worksheet Krajnji_Ukupno = krajnjiExcel.Sheets["Ukupno po mjesecima"];//sheet ukupno
Excel.Range brojRedovaPolazni = Polazni.UsedRange;
int brojacRedovaPolazni = brojRedovaPolazni.Rows.Count; //broj redova u polaznom excelu
Excel.Range brojRedovaKrajnjiMT = Krajnji_PoMT.UsedRange;
int brojacRedovaKrajnjiMT = brojRedovaKrajnjiMT.Rows.Count;//broj redova u krajnjem excelu sheet mjesto troska
Excel.Range brojRedovaKrajnjiUkupno = Krajnji_Ukupno.UsedRange;
int brojacRedovaKrajnjiUkupno = brojRedovaKrajnjiUkupno.Rows.Count;//broj redova u krajnjem excelu sheet ukupno
List<string> listaMT = new List<string>();
List<string> PostojeciMjeseci = new List<string>(); //tu planiram trpati mjesece koji postoje
if (brojacRedovaPolazni == brojacRedovaKrajnjiMT)
{
for (int i = 1; i <= 12; i++)
{
if(Polazni.Cells[9, i + 2].Value != null || Polazni.Cells[9, i + 2].Value != "")
{
listaMT.Add(Polazni.Cells[9, i + 2].Value);
}
}
PostojeciMjeseci = mjeseci.Intersect(listaMT).ToList(); //ovi mjeseci postoje
int kolumna = 0;
for (int i = 0; i < PostojeciMjeseci.Count; i++)
{
for (int j = 1; j < 12; j++)
{
//MessageBox.Show(Polazni.Cells[9, j + 2].Value);
if (string.Equals(PostojeciMjeseci[i], Polazni.Cells[9, j + 2].Value))
{
#region Broj kolumne
if (string.Equals(Polazni.Cells[9, j + 2].Value, "siječanj")) kolumna = 3;//"C";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "veljača")) kolumna = 4;// "D";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "ožujak")) kolumna = 5;// "E";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "travanj")) kolumna = 6;// "F";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "svibanj")) kolumna = 7;// "G";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "lipanj")) kolumna = 8;// "H";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "srpanj")) kolumna = 9;// "I";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "kolovor")) kolumna = 10;// "J";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "rujan")) kolumna = 11;// "K";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "listopad")) kolumna = 12;// "L";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "studeni")) kolumna = 13;// "M";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "prosinac")) kolumna = 14;// "N";
#endregion
//MessageBox.Show("U petlji: "+Polazni.Cells[9, j + 2].Value);
string sValue = "";
for (int x = 1; x <= brojacRedovaKrajnjiMT - 12; x++)
{
Krajnji_PoMT.Cells[(x + 12), kolumna].Value = Polazni.Cells[(x + 12), kolumna].Value;
}
}
}
}
}
else if (brojacRedovaPolazni == brojacRedovaKrajnjiUkupno)
{
for (int i = 1; i <= brojacRedovaKrajnjiUkupno; i++)
{
}
}
else
{
MessageBox.Show("Broj redova nije konzistentan s glavnom tablicom.");
}
polazna.Close(true, Type.Missing, Type.Missing);
krajnja.Close(true, Type.Missing, Type.Missing);
polazniExcel.Quit();
krajnjiExcel.Quit();
}
else
{
MessageBox.Show("Unesite obe putanje do Excel datoteka.");
}
}
My problem is in the line:
Krajnji_PoMT.Cells[(x + 12), kolumna].Value = Polazni.Cells[(x + 12), kolumna].Value;
I tried many variations but I can never get that value pasted to another Excel. If I say:
Krajnji_PoMT.Cells[(x + 12), kolumna].Value = "test";
then it works. Whats the catch here?

Export Formatted DataGridView To Excel

I have a DataGridView which has a few rows in Red Color, Blue Color etc. I need to export DataGridView with this exact formatting to an excel sheet, My code is written below but is not working please help me.
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == DialogResult.OK)
{
string stOutput = "";
// Export titles:
string sHeaders = "";
for (int j = 0; j < dgvImportData.Columns.Count; j++)
sHeaders = sHeaders.ToString() + Convert.ToString(dgvImportData.Columns[j].HeaderText) + "\t";
stOutput += sHeaders + "\r\n";
// Export data.
if (Status == 1)
{
for (int i = 0; i < dgvImportData.RowCount; i++)
{
if (Convert.ToInt32(dgvImportData.Rows[i].Cells["Status"].Value) == Status)
{
string stLine = "";
for (int j = 0; j < dgvImportData.Rows[i].Cells.Count; j++)
stLine = stLine.ToString() + Convert.ToString(dgvImportData.Rows[i].Cells[j].Value) + "\t";
stOutput += stLine + "\r\n";
}
}
}
else
{
for (int i = 0; i < dgvImportData.RowCount; i++)
{
if (Convert.ToInt32(dgvImportData.Rows[i].Cells["Status"].Value) == Status)
{
string stLine = "";
for (int j = 0; j < dgvImportData.Rows[i].Cells.Count; j++)
stLine = stLine.ToString() + Convert.ToString(dgvImportData.Rows[i].Cells[j].Value) + "\t";
stOutput += stLine + "\r\n";
}
}
}
Encoding utf16 = Encoding.GetEncoding(1254);
byte[] output = utf16.GetBytes(stOutput);
FileStream fs = new FileStream(sfd.FileName, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(output, 0, output.Length); //write the encoded file
bw.Flush();
bw.Close();
fs.Close();
Add Microsoft.Office.Interop.Excel.dll to your project.
Add the following using statement:
using Excel = Microsoft.Office.Interop.Excel;
Now add the following function to convert integer to Excel Column letter:
private string GetExcelColumnName(int columnNumber)
{
int dividend = columnNumber;
string columnName = String.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
dividend = (int)((dividend - modulo) / 26);
}
return columnName;
}
Then add the following function to proceed to the export
private void ExportToExcel(DataGridView dv)
{
Excel.Application xlApp;
xlApp = new Excel.Application();
xlApp.Visible = true;
xlApp.AskToUpdateLinks = false;
xlApp.DisplayAlerts = false;
Excel.Workbook wb = (Excel.Workbook)xlApp.Workbooks.Add();
Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets.Add();
int rowstartindex = 1;
//Create headers
for (int i = 0; i < dv.Columns.Count; i++)
{
Excel.Range CellHeadersRange = ws.get_Range(GetExcelColumnName(i+1) + rowstartindex.ToString(), GetExcelColumnName(i+1) + rowstartindex.ToString());
CellHeadersRange.Value = dv.Columns[i].HeaderText;
}
//Write data
for (int i = 0; i < dv.Rows.Count; i++)
{
for (int j = 0; j < dv.Columns.Count; j++)
{
Excel.Range CellDataRange = ws.get_Range(GetExcelColumnName(j+1) + (i+rowstartindex+1).ToString());
CellDataRange.Value = dv[j, i].Value;
//Verify that backgroundcolor of datagrid is not RGB(0,0,0,0) and in that case apply datagridviewcell color to excel range
if(!dv.Rows[i].Cells[j].Style.BackColor.IsEmpty)
CellDataRange.Interior.Color = dv.Rows[i].Cells[j].Style.BackColor;
//Verify that font style exist before checking for bold and in that case apply datagridviewcell font.bold property to excel range
if(dv.Rows[i].Cells[j].Style.Font != null)
CellDataRange.Font.Bold = dv.Rows[i].Cells[j].Style.Font.Bold;
}
}
wb = null;
ws = null;
xlApp = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
Once you understand the logic here, it's then easy to apply more style/formatting of your datagridview to the excel range.

Drag formulas in excel from C#

I have a feeling that this question is very simple, but I just can't find the answer.
I want to apply a column of formulas in column "C" based on information in col "A" and "B". I want the formula to work as it would in excel when you write a formula, and then drag, creating row-relative formulas all the way down.
The method below works, but it's very slow, since it writes each formula separately. I'm sure there's a more efficient method out there somewhere.
Thanks
using Excel = Microsoft.Office.Interop.Excel;
...
object oOpt = System.Reflection.Missing.Value; //for optional arguments
Excel.Application oXL = null;
Excel.Workbook oWB = null;
Excel.Worksheet oSheet = null;
Excel.Range oRng = null;
try
{
//Start Excel and get Application object.
oXL = new Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Excel.Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
...
//Set numberOfRows
//Load information to column A and B
...
//Write the column of formulas
for (int r = 2; r < numberOfRows + 2; r++)
{
oRng = oSheet.get_Range("C" + r, "C" + r);
oRng.Formula = "= IF(AND(A" + r + "<> 0,B" + r + "<>2),\"YES\",\"NO\")";
}
}
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");
}
finally
{
// Cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.FinalReleaseComObject(oRng);
Marshal.FinalReleaseComObject(oSheet);
oWB.Close(Type.Missing, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(oWB);
oXL.Quit();
Marshal.FinalReleaseComObject(oXL);
}
Use R1C1 formula, and replace :
for (int r = 2; r < numberOfRows + 2; r++)
{
oRng = oSheet.get_Range("C" + r, "C" + r);
oRng.Formula = "= IF(AND(A" + r + "<> 0,B" + r + "<>2),\"YES\",\"NO\")";
}
with
oRng = oSheet.get_Range("C2").get_Resize(100, 1);
oRng.FormulaR1C1 = "=IF(AND(RC[-2]<> 0,RC[-1]<>2),\"YES\",\"NO\")";
I am posting this code for Drag formulas in excel from C# using Microsoft.Office.Interop.Excel Library
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.Excel();
}
public void Excel()
{
Application xlApp = new Application();
Workbook xlWorkBook;
Worksheet xlWorkSheet;
object misValue = Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (int r = 1; r < 5; r++) //r stands for ExcelRow and c for ExcelColumn
{
// Its a my sample example: Excel row and column start positions for writing Row=1 and Col=1
for (int c = 1; c < 3; c++)
{
if (c == 2)
{
if (r == 1)
{
xlWorkSheet.Cells[r, c].Formula = "=SUM(A1+200)";
}
continue;
}
xlWorkSheet.Cells[r, c] = r;
}
}
Range rng = xlWorkSheet.get_Range("B1");
// This is the main code we can Drag our excel sheet formulas in range
rng.AutoFill(xlWorkSheet.get_Range("B1", "B4"), XlAutoFillType.xlLinearTrend);
xlWorkBook.Worksheets[1].Name = "MySheetData";//Renaming the Sheet1 to MySheet
xlWorkBook.SaveAs(#"E:\test.xlsx");
xlWorkBook.Close();
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
}
}

range.find method in Excel

I have an Excel file with headers
Sep-08 Oct-08 Nov-08 Dec-08 Jan-09 Feb-09 Mar-09 Apr-09
i want to pass a string say Dec-08 and get the address of the cells where this is present in a range.
Iam using range.find method but not able to find the date in Excel. Any help would be appreciated
//Declare these two variables globally so you can access them from both
//Button1 and Button2.
Excel.Application objApp;
Excel._Workbook objBook;
private void button1_Click(object sender, System.EventArgs e)
{
Excel.Workbooks objBooks;
Excel.Sheets objSheets;
Excel._Worksheet objSheet;
Excel.Range range;
try
{
// Instantiate Excel and start a new workbook.
objApp = new Excel.Application();
objBooks = objApp.Workbooks;
objBook = objBooks.Add( Missing.Value );
objSheets = objBook.Worksheets;
objSheet = (Excel._Worksheet)objSheets.get_Item(1);
//Get the range where the starting cell has the address
//m_sStartingCell and its dimensions are m_iNumRows x m_iNumCols.
range = objSheet.get_Range("A1", Missing.Value);
range = range.get_Resize(5, 5);
if (this.FillWithStrings.Checked == false)
{
//Create an array.
double[,] saRet = new double[5, 5];
//Fill the array.
for (long iRow = 0; iRow < 5; iRow++)
{
for (long iCol = 0; iCol < 5; iCol++)
{
//Put a counter in the cell.
saRet[iRow, iCol] = iRow * iCol;
}
}
//Set the range value to the array.
range.set_Value(Missing.Value, saRet );
}
else
{
//Create an array.
string[,] saRet = new string[5, 5];
//Fill the array.
for (long iRow = 0; iRow < 5; iRow++)
{
for (long iCol = 0; iCol < 5; iCol++)
{
//Put the row and column address in the cell.
saRet[iRow, iCol] = iRow.ToString() + "|" + iCol.ToString();
}
}
//Set the range value to the array.
range.set_Value(Missing.Value, saRet );
}
//Return control of Excel to the user.
objApp.Visible = true;
objApp.UserControl = true;
}
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" );
}
}

Categories

Resources