range.find method in Excel - c#

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

Related

Clipboard multiple DataGridViews to excel using Interop.Excel

in this part im exporting a DataGridView data and pasting it in a new excel file, my problem is that i wanna export three more DataGridViews to the same excel file and sheet, any suggestion?
private void exportclipboard()
{
dataGridView1.SelectAll();
dataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
dataGridView1.MultiSelect = true;
dataGridView1.SelectAll();
DataObject dataobj = dataGridView2.GetClipboardContent();
if (dataobj != null)
Clipboard.SetDataObject(dataobj);
}
private void btn_guardar_Click(object sender, EventArgs e)
{
int i = 0;
if(i == 0)
{
exportclipboard();
Excel.Application excel;
Excel.Workbook workbook;
Excel.Worksheet worksheet;
object missvalue = System.Reflection.Missing.Value;
excel = new Excel.Application();
excel.Visible = true;
workbook = excel.Workbooks.Add(missvalue);
worksheet = (Excel.Worksheet)workbook.Worksheets.get_Item(1); //number of sheet
Excel.Range CR = (Excel.Range)worksheet.Cells[1, 1]; //This is the position where the data will be pasted
CR.Select();
worksheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
i++;
}
}
I found a way to export four DataGridViews to excel with a saveDialog implement, but the loops are slow. Any improvement is welcome.
private void ExportarExcel()
{
// Creating a Excel object.
Excel._Application excel = new Excel.Application();
Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing);
Excel._Worksheet worksheet = null;
try
{
worksheet = workbook.ActiveSheet;
worksheet.Name = "ExportedFromDatGrid";
int cellRowIndex = 1;
int cellColumnIndex = 1;
//Loop through each row and read value from each column.
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
// Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check.
if (cellRowIndex == 1)
{
worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Columns[j].HeaderText;
}
else
{
worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
cellColumnIndex++;
}
cellColumnIndex = 1;
cellRowIndex++;
}
//DATAGRIDVIEW2
int cellRowIndex1 = 1;
int cellColumnIndex1 = 3;
//Loop through each row and read value from each column.
for (int i = 0; i < dataGridView2.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView2.Columns.Count; j++)
{
// Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check.
if (cellRowIndex1 == 1)
{
worksheet.Cells[cellRowIndex1, cellColumnIndex1] = dataGridView2.Columns[j].HeaderText;
}
else
{
worksheet.Cells[cellRowIndex1, cellColumnIndex1] = dataGridView2.Rows[i].Cells[j].Value.ToString();
}
cellColumnIndex1++;
}
cellColumnIndex1 = 3;
cellRowIndex1++;
}
//DATAGRIDVIEW3
int cellRowIndex2 = 1;
int cellColumnIndex2 = 5;
//Loop through each row and read value from each column.
for (int i = 0; i < dataGridView3.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView3.Columns.Count; j++)
{
// Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check.
if (cellRowIndex2 == 1)
{
worksheet.Cells[cellRowIndex2, cellColumnIndex2] = dataGridView3.Columns[j].HeaderText;
}
else
{
worksheet.Cells[cellRowIndex2, cellColumnIndex2] = dataGridView3.Rows[i].Cells[j].Value.ToString();
}
cellColumnIndex2++;
}
cellColumnIndex2 = 5;
cellRowIndex2++;
}
//DATAGRIDVIEW4
int cellRowIndex3 = 1;
int cellColumnIndex3 = 7;
//Loop through each row and read value from each column.
for (int i = 0; i < dataGridView4.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView4.Columns.Count; j++)
{
// Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check.
if (cellRowIndex3 == 1)
{
worksheet.Cells[cellRowIndex3, cellColumnIndex3] = dataGridView4.Columns[j].HeaderText;
}
else
{
worksheet.Cells[cellRowIndex3, cellColumnIndex3] = dataGridView4.Rows[i].Cells[j].Value.ToString();
}
cellColumnIndex3++;
}
cellColumnIndex3 = 7;
cellRowIndex3++;
}
//Getting the location and file name of the excel to save from user.
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
saveDialog.FilterIndex = 2;
if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
workbook.SaveAs(saveDialog.FileName);
MessageBox.Show("Export Successful");
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
excel.Quit();
workbook = null;
excel = null;
}
}

Transform DataTable to Excel not include headercells

I am trying to transform a datatbale to Excel using this funtion
internal static bool DataTableToExcel(System.Data.DataTable dataTable, string path)
{
_Excel.Application objXL = objXL = new _Excel.Application();
_Excel.Workbook objWB = null;
_Excel.Worksheet ExcelWorkSheet = null;
try
{
objWB = objXL.Workbooks.Add(_Excel.XlWBATemplate.xlWBATWorksheet);
ExcelWorkSheet = objWB.Worksheets[1];
for (int i = 0; i < dataTable.Rows.Count; i++)
{
for (int j = 0; j < dataTable.Columns.Count; j++)
{
ExcelWorkSheet.Cells[i + 1, j + 1] = dataTable.Rows[i][j].ToString();
}
}
objWB.SaveAs(path);
objWB.Close();
objXL.Quit();
return true;
}
catch(Exception ex)
{
objWB.Close();
objXL.Quit();
return false;
}
}
But the final result is missing the header cells in the document: I am only obtaining the date but i need to add the header cells in the excell document too.
In this case I believe you are missing adding the columns names before start the loop in your rows.
Try something like this for sheet's first row:
ExcelWorkSheet.Cells[0,0] = datatable.Columns["columnName"].ColumnName

Move the number in the cell to right side in excel table

I'm trying to move my numbers(double type) to right side of cell.I take all data from datagridview and put it in my excel table
An excel table includes 5 columns. In the first are strings and the rest of them are numbers of int and double type.
If I have a number with coma in my cell,is the number on the right side,and numbers without coma are on the left side.
I've read I can use something like this one --> myRange.FormatNumber.
But I don't now how I can use this...
try {
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
saveFileDialog1.InitialDirectory = path;
saveFileDialog1.Title = "Als Excel Datei speichern";
saveFileDialog1.FileName = "";
saveFileDialog1.Filter = "Excel Files(2013)|*.xlsx|Excel Files(2003)|*.xls|Excel Files(2007)|*.xlsx";
if (saveFileDialog1.ShowDialog() != DialogResult.Cancel)
{
Cursor.Current = Cursors.WaitCursor;
Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
ExcelApp.Application.Workbooks.Add(Type.Missing);
object[,] arr = new object[maximaleZeilenAnzahl, maximaleSpaltenAnzahl]; //Array erstellen
//Überschrift Tabelle Einzeln
for (int columnIndex = 0; columnIndex < dgvEinzeln.Columns.Count; columnIndex++)
{
arr[aktuelleExcelZeile, columnIndex] = dgvEinzeln.Columns[columnIndex].HeaderText;
}
aktuelleExcelZeile += 1;
//Tabelle Einzeln
for (int rowIndex = 0; rowIndex < dgvEinzeln.Rows.Count; rowIndex++)
{
for (int columnIndex = 0; columnIndex < dgvEinzeln.Columns.Count; columnIndex++)
{
arr[aktuelleExcelZeile, columnIndex] = dgvEinzeln.Rows[rowIndex].Cells[columnIndex].Value.ToString();
}
aktuelleExcelZeile++;
}
aktuelleExcelZeile += 5;
//Überschrift Tabelle Summe
for (int columnIndex = 0; columnIndex < dgvSumme.Columns.Count; columnIndex++)
{
arr[aktuelleExcelZeile, columnIndex] = dgvSumme.Columns[columnIndex].HeaderText;
}
aktuelleExcelZeile += 1;
//Tabelle Summe
for (int rowIndex = 0; rowIndex < dgvSumme.Rows.Count; rowIndex++)
{
for (int columnIndex = 0; columnIndex < dgvSumme.Columns.Count; columnIndex++)
{
arr[aktuelleExcelZeile, columnIndex] = dgvSumme.Rows[rowIndex].Cells[columnIndex].Value.ToString();
}
aktuelleExcelZeile++;
}
Range c1 = (Range)ExcelApp.Cells[1, 1];
Range c2 = (Range)ExcelApp.Cells[aktuelleExcelZeile, maximaleSpaltenAnzahl];
Range range = ExcelApp.get_Range(c1, c2);
range.Value = arr;
ExcelApp.ActiveWorkbook.SaveCopyAs(saveFileDialog1.FileName.ToString());
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
string filename = Path.GetFullPath(saveFileDialog1.FileName);
System.Diagnostics.Process.Start(filename);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
throw;
}
finally
{
Cursor.Current = Cursors.Default;
}
Please try this one
ExcelApp.Cells[rownumbwe, columnNumber].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignRight;

exporting calculated GridView column to Excel gives empty values

I have a GridView data with an additional calculated column. I'd like to export GridView to Excel. It returns empty values for the calculated column only. Any help will be appreciated! Thanks in advance.
Here is the code I used to export to Excel.
protected void ExportToExcel(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();
Workbook wb = Excel.Workbooks.Add(XlSheetType.xlWorksheet);
Worksheet ws = (Worksheet)Excel.ActiveSheet;
ws.Cells.Font.Size = 10;
Excel.ScreenUpdating = false;
GridView3.AllowPaging = false;
GridView3.DataBind();
for (int i = 1; i < GridView3.Columns.Count + 1; i++)
{
ws.Cells[1, i] = GridView3.Columns[i - 1].HeaderText;
ws.Cells[1, i].Characters.Font.Bold = true;
}
for (int i = 0; i < GridView3.Rows.Count; i++)
{
for (int j = 0; j < GridView3.Columns.Count; j++)
{
ws.Cells[i + 2, j + 1] = HttpUtility.HtmlDecode(GridView3.Rows[i].Cells[j].Text.ToString());
}
}
GridView3.AllowPaging = true;
GridView3.DataBind();
ws.EnableAutoFilter = true;
ws.Range["A1", "A1"].AutoFilter(1, Type.Missing);
ws.Columns.AutoFit();
Excel.ScreenUpdating = true;
Excel.Visible = true;
}

Export datagrid to a excel window which is opening c#

I'm begining in WPF and i'm working with datagrid
I have multi datagrids. If i click a button ("Export" button) first time, it will create a new excel window and export data to first sheet. Then, i change to another datagrid and click a button ("Export" button) second time. so, it will create a new sheet in excel window which created before. Can you help me change my code ?
Thank you very much!!
public void Export(DataTable dt, string sheetName, string title)
{
Microsoft.Office.Interop.Excel.Application oExcel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbooks oBooks;
Microsoft.Office.Interop.Excel.Sheets oSheets;
Microsoft.Office.Interop.Excel.Workbook oBook;
Microsoft.Office.Interop.Excel.Worksheet oSheet;
Excel.Range _range = null;
oExcel.DisplayAlerts = false;
oExcel.Application.SheetsInNewWorkbook = 1;
oBooks = oExcel.Workbooks;
oBook = (Microsoft.Office.Interop.Excel.Workbook)(oExcel.Workbooks.Add(Type.Missing));
oSheets = oBook.Worksheets;
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oSheets.get_Item(1);
oSheet.Name = sheetName;
Microsoft.Office.Interop.Excel.Range head = oSheet.get_Range("A1", "C1");
head.MergeCells = true;
head.Value2 = title;
head.Font.Bold = true;
head.Font.Name = "Tahoma";
head.Font.Size = "18";
head.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
List<object> objHeaders = new List<object>();
for (int n = 0; n <= dt.Rows.Count; n++)
{
objHeaders.Add(dt.Columns[n].ColumnName);
}
var headerToAdd = objHeaders.ToArray();
_range = oSheet.get_Range("A3", Type.Missing);
_range = _range.get_Resize(dt.Rows.Count, dt.Columns.Count);
_range.ColumnWidth = 30;
_range.set_Value(Type.Missing, headerToAdd);
Excel.Range rowHead = oSheet.get_Range("A3", "C"+dt.Columns.Count);
rowHead.Font.Bold = true;
rowHead.Borders.LineStyle = Microsoft.Office.Interop.Excel.Constants.xlSolid;
rowHead.Interior.ColorIndex = 15;
rowHead.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
int row = dt.Rows.Count;
int col = dt.Columns.Count;
object[,] arr = new object[row, col];
for (int r = 0; r < dt.Rows.Count; r++)
{
DataRow dr = dt.Rows[r];
for (int c = 0; c < dt.Columns.Count; c++)
{
arr[r, c] = dr[c];
}
}
int rowStart = 4;
int columnStart = 1;
int rowEnd = rowStart + dt.Rows.Count - 1;
int columnEnd = dt.Columns.Count;
Microsoft.Office.Interop.Excel.Range c1 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[rowStart, columnStart];
Microsoft.Office.Interop.Excel.Range c2 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[rowEnd, columnEnd];
Microsoft.Office.Interop.Excel.Range range = oSheet.get_Range(c1, c2);
range.Value2 = arr;
range.Borders.LineStyle = Microsoft.Office.Interop.Excel.Constants.xlSolid;
Microsoft.Office.Interop.Excel.Range c3 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[rowEnd, columnStart];
Microsoft.Office.Interop.Excel.Range c4 = oSheet.get_Range(c1, c3);
oSheet.get_Range(c3, c4).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
oExcel.Visible = true;
}
}
You need to use field Microsoft.Office.Interop.Excel.Application oExcel in your class to store its value. First time it will be null, but on second - it will be opened excel. But you must be carefull with such a behavior, user can close excel, before 2nd export. So you need implement Closed event handler and clear your field (similar problem)

Categories

Resources