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
Related
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;
}
}
I make to get data excel with C# winform.
private void ReleaseExcelObject(object obj)
{
try
{
if (obj != null)
{
Marshal.ReleaseComObject(obj);
obj = null;
}
}
catch (Exception ex)
{
obj = null;
throw ex;
}
}
private void buttonOpen_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application application = null;
Workbook workBook = null;
int tempNum = 0;
try
{
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() != DialogResult.OK)
return;
application = new Microsoft.Office.Interop.Excel.Application();
application.Visible = true;
workBook = application.Workbooks.Open(dlg.FileName);
Worksheet newWorkSheet = workBook.Worksheets.Add(After: workBook.Worksheets.Item[workBook.Worksheets.Count]);
int newSheetRow = 0;
Dictionary<int, string> upData = new Dictionary<int, string>();
for (int sheetIndex = 1; sheetIndex<workBook.Worksheets.Count; sheetIndex++)
{
for (int row = 1; row < workBook.Worksheets[sheetIndex].UsedRange.Rows.Count; row++)
{
upData.Add(row, null);
for (int col = 1; col < workBook.Worksheets[sheetIndex].UsedRange.Columns.Count; col++)
{
tempNum++;
if (workBook.Worksheets[sheetIndex].Cells[col, row] != null)
{
string cellData = workBook.Worksheets[sheetIndex].Cells[col, row].value;
string[] datas = cellData.Split(' ');
string dataName = null;
for (int k = 1; k < datas.Length; k++)
{
dataName += datas[k];
}
string icd11 = datas[0];
newWorkSheet.Cells[newSheetRow,0] = icd11;
newWorkSheet.Cells[newSheetRow,1] = dataName;
newWorkSheet.Cells[newSheetRow,2] = upData[col - 1];
upData[col] = dataName;
continue;
}
}
}
}
}
catch (Exception exc)
{
MessageBox.Show(tempNum + exc.Message);
}
finally
{
ReleaseExcelObject(workBook);
ReleaseExcelObject(application);
}
}
The part where the error occurs is
MessageBox.Show(workBook.Sheets[0].ToString());
this part.
And force workBookSheet.getitem("hardCording").
If you do this, an error occurs in the part of direct data access of the cell.
I wonder how I can query and insert excel data.
The error is Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))
Excel data:
edit sheet[0]
sheet[0] is not able
i don't understand VBA
how to implement this
excel treeExample
Worksheet newWorkSheet = workBook.Worksheets.Add(After: workBook.Worksheets.Item[workBook.Worksheets.Count]);
int newSheetRow = 1;
Dictionary<int, string> upData = new Dictionary<int, string>();
for (int sheetIndex = 1; sheetIndex<workBook.Worksheets.Count; sheetIndex++)
{
int rowMax=workBook.Worksheets[sheetIndex].UsedRange.Rows.Count;
int colMax = workBook.Worksheets[sheetIndex].UsedRange.Columns.Count;
for (int i = 0; i < workBook.Worksheets[sheetIndex].UsedRange.Rows.Count; i++)
upData.Add(i, "000000");
for (int row = 1; row < workBook.Worksheets[sheetIndex].UsedRange.Rows.Count; row++)
{
for (int col = 1; col < workBook.Worksheets[sheetIndex].UsedRange.Columns.Count; col++)
{
tempRow = row;
tempCol = col;
if (workBook.Worksheets[sheetIndex].Cells[row, col] != null)
{
Range cell = workBook.Worksheets[sheetIndex].Cells[row, col];
string cellData = cell.Value;
if (cellData != null)
{
string[] datas = cellData.Split(null);
string dataName = null;
for (int k = 1; k < datas.Length; k++)
{
dataName += datas[k];
}
string icd11 = datas[0];
Range newCellData1 = newWorkSheet.Cells[newSheetRow, 1];
newCellData1.Value = icd11;
Range newCellData2 = newWorkSheet.Cells[newSheetRow, 2];
newCellData2.Value = dataName;
Range newCellData3 = newWorkSheet.Cells[newSheetRow, 3];
newCellData3.Value = upData[col - 1];
upData[col] = datas[0];
newSheetRow++;
}
continue;
}
}
}
upData.Clear();
}
}
excel debug is not work in visual studio
I fixed the bugs in my code.
cell. value and these sub-items are not visible
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;
I want to extract some data in the datatable, and want to send the email.
But when I extract the data, excel has many blanks between the extracted data.
The data which is not extracted make a blank row.
When I try to use RemoveRow() function, it doesn't work and still has a blank row.
private void Email()
{
//get the data from database
DataTable data = GetData();
int maxLavel = Convert.ToInt32(data.Compute("max([AssignedID])", string.Empty));
IWorkbook workbook;
workbook = new HSSFWorkbook();
for (int Emp = 0; Emp < maxLavel; Emp++)
{
ISheet sheet1 = workbook.CreateSheet("Sheet 1");
int num = 0;
//make a header row
IRow row1 = sheet1.CreateRow(0);
for (int j = 0; j < data.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
String columnName = data.Columns[j].ToString();
cell.SetCellValue(columnName);
}
//loops through data
for (int i = 0; i < data.Rows.Count; i++)
{
IRow row = sheet1.CreateRow(i + 1);
if (Emp == Convert.ToInt32(data.Rows[i][0]))
{
num++;
ICell cell = row.CreateCell(j);
for (int j = 0; j < data.Columns.Count; j++)
{
sheet1.AutoSizeColumn(j); //control cell width
String columnName = data.Columns[j].ToString();
cell.SetCellValue(data.Rows[i][columnName].ToString());
}
}
else ///here has problems
{
var row = sheet1.GetRow(i);
//sheet1.RemoveRow(row);
sheet1.ShiftRows(i + 1, sheet1.LastRowNum + 1, -1);
}
}
if (num != 0)
{
//send email
}
}
}
I'm not sure why you need to resend the same file again with different contents instead of simply sending a different file, but could you perhaps try moving the creation of your sheet inside the for loop, and try removing the entire sheet instead? E.g. something like this:
private void Email()
{
//get the data from database
DataTable data = GetData();
int maxLavel = Convert.ToInt32(data.Compute("max([AssignedID])", string.Empty));
IWorkbook workbook;
workbook = new HSSFWorkbook();
for (int Emp = 0; Emp < maxLavel; Emp++)
{
ISheet sheet1 = workbook.CreateSheet("Sheet 1");
int num = 0;
//make a header row
IRow row1 = sheet1.CreateRow(0);
for (int j = 0; j < data.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
String columnName = data.Columns[j].ToString();
cell.SetCellValue(columnName);
}
//loops through data
for (int i = 0; i < data.Rows.Count; i++)
{
IRow row = sheet1.CreateRow(i + 1);
if (Emp == Convert.ToInt32(data.Rows[i][0]))
{
num++;
for (int j = 0; j < data.Columns.Count; j++)
{
ICell cell = row.CreateCell(j);
sheet1.AutoSizeColumn(j); //control cell width
String columnName = data.Columns[j].ToString();
cell.SetCellValue(data.Rows[i][columnName].ToString());
}
}
}
if (num != 0)
{
//send email
}
workbook.remove(sheet1);
}
}
I figure it out..I don't need to remove the row.
IRow row = sheet1.CreateRow(i);
This should be changed.
for (int i = 0; i < data.Rows.Count; i++)
{
if (Emp == Convert.ToInt32(data.Rows[i][0]))
{
IRow row = sheet1.CreateRow(row_num);
num++; row_num++;
for (int j = 0; j < data.Columns.Count; j++)
{
ICell cell = row.CreateCell(j);
sheet1.AutoSizeColumn(j); //control cell width
String columnName = data.Columns[j].ToString();
cell.SetCellValue(data.Rows[i][columnName].ToString());
}
}
}
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" );
}
}