How can i export multiple dataset to an excel sheet - c#

Hi all i would like to export the data from the dataset to excel sheet. My dataset consists of 2 Tables so how can i write the multiple dataset values in a single excel sheet

before u have to create
1.using Excel = Microsoft.Office.Interop.Excel;//in header,and Add correct refference
2.Excel.Application excelHandle1 = PrepareForExport(Ds); //add handle in calling function
excelHandle1.Visible = true;
public Excel.Application PrepareForExport(System.Data.DataSet ds,string[] sheet)
{
object missing = System.Reflection.Missing.Value;
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Add(missing);
DataTable dt1 = new DataTable();
dt1 = ds.Tables[0];
DataTable dt2 = new DataTable();
dt2 = ds.Tables[1];
Excel.Worksheet newWorksheet;
newWorksheet = (Excel.Worksheet)excel.Worksheets.Add(missing, missing, missing, missing);
newWorksheet.Name ="Name of data sheet";
// for first datatable dt1..
int iCol1 = 0;
foreach (DataColumn c in dt1.Columns)
{
iCol1++;
excel.Cells[1, iCol1] = c.ColumnName;
}
int iRow1 = 0;
foreach (DataRow r in dt1.Rows)
{
iRow1++;
for (int i = 1; i < dt1.Columns.Count + 1; i++)
{
if (iRow1 == 1)
{
// Add the header the first time through
excel.Cells[iRow1, i] = dt1.Columns[i - 1].ColumnName;
}
excel.Cells[iRow1 + 1, i] = r[i - 1].ToString();
}
}
// for second datatable dt2..
int iCol2 = 0;
foreach (DataColumn c in dt2.Columns)
{
iCol2++;
excel.Cells[1, iCol] = c.ColumnName;
}
int iRow2 = 0;
foreach (DataRow r in dt2.Rows)
{
iRow2++;
for (int i = 1; i < dt2.Columns.Count + 1; i++)
{
if (iRow2 == 1)
{
// Add the header the first time through
excel.Cells[iRow2, i] = dt2.Columns[i - 1].ColumnName;
}
excel.Cells[iRow2 + 1, i] = r[i - 1].ToString();
}
}
return excel;
}
i am using this code

Instead of single Excel Sheet,you can write a Table values in each sheet,
http://csharp.net-informations.com/excel/csharp-excel-export.htm
increment the worksheet count you able to save multiple dataset values in the single excel file.
Hope it may help to you.

Related

get value from data table specific cell and output to textbox

trying to get a value from a data table, and output its contents to a textbox. seems im nearly there but for some reason studio doesnt like dt.rows[][];
ive seen multiple examples online in this format, but i get error CS002, cannot apply indexing with [] to an expression of type 'DataGridViewRow'.
im trying to locate the current row, and i can figure out the column either by putting an index number or by using the name of the column if that works better.
here is datatable_selectionChanged
private void dt_SelectionChanged(object sender, EventArgs e)
{
int row = dt.CurrentCell.RowIndex;
int col = dt.CurrentCell.ColumnIndex;
textBox1.Text = Convert.ToString(row);
textBox2.Text = Convert.ToString(col);
}
here is my mainform_load
private void mainForm_Load(object sender, EventArgs e)
{
string file = #"C:\Users\User\OneDrive - Motion Controls Robotics, Inc\Desktop\test inventory\TIS.xlsm"; //variable for the Excel File Location
DataTable dt = new DataTable(); //container for our excel data
DataRow row;
try
{
//Create Object for Microsoft.Office.Interop.Excel that will be use to read excel file
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(file);
Microsoft.Office.Interop.Excel._Worksheet excelWorksheet = excelWorkbook.Sheets[1];
Microsoft.Office.Interop.Excel.Range excelRange = excelWorksheet.UsedRange;
int rowCount = excelRange.Rows.Count; //get row count of excel data
int colCount = excelRange.Columns.Count;//number of columns to display
//Get the first Column of excel file which is the Column Name
for (int i = 2; i <= rowCount;)
{
for (int j = 1; j <= colCount; j++)
{
dt.Columns.Add(excelRange.Cells[i, j].Value2.ToString());
}
break;
}
//Get Row Data of Excel
int rowCounter; //This variable is used for row index number
for (int i = 3; i <= rowCount; i++) //Loop for available row of excel data
{
row = dt.NewRow(); //assign new row to DataTable
rowCounter = 0;
for (int j = 1; j <= colCount; j++) //Loop for available column of excel data
{
//check if cell is empty
if (excelRange.Cells[i, j] != null && excelRange.Cells[i, j].Value2 != null)
{
row[rowCounter] = excelRange.Cells[i, j].Value2.ToString();
}
else
{
excelRange.Cells[i, j].value2 = "Empty";
//row[i] = "";
}
rowCounter++;
}
dt.Rows.Add(row); //add row to DataTable
}
this.dt.DataSource = dt; //assign DataTable as Datasource for DataGridview
//close and clean excel process
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.ReleaseComObject(excelRange);
Marshal.ReleaseComObject(excelWorksheet);
//quit apps
excelWorkbook.Close();
Marshal.ReleaseComObject(excelWorkbook);
excelApp.Quit();
Marshal.ReleaseComObject(excelApp);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

How to read Excel to Datatable using NPOI C#

I'm Trying to read Excel to DataTable using NPOI.Every thing working fine but only issue is If we have any Column cell is empty in that row it is not reading .In Excel i have 4 row's with (each row have some empty values for cells).
Excel File Image : enter image description here
After Reading That Excel To data table :enter image description here
I want like this in data table
private DataTable GetDataTableFromExcel(String Path)
{
XSSFWorkbook wb;
XSSFSheet sh;
String Sheet_name;
using (var fs = new FileStream(Path, FileMode.Open, FileAccess.Read))
{
wb = new XSSFWorkbook(fs);
Sheet_name = wb.GetSheetAt(0).SheetName; //get first sheet name
}
DataTable DT = new DataTable();
DT.Rows.Clear();
DT.Columns.Clear();
// get sheet
sh = (XSSFSheet)wb.GetSheet(Sheet_name);
int i = 0;
while (sh.GetRow(i) != null)
{
// add neccessary columns
if (DT.Columns.Count < sh.GetRow(i).Cells.Count)
{
for (int j = 0; j < sh.GetRow(i).Cells.Count; j++)
{
DT.Columns.Add("", typeof(string));
}
}
// add row
DT.Rows.Add();
// write row value
for (int j = 0; j < sh.GetRow(i).Cells.Count; j++)
{
var cell = sh.GetRow(i).GetCell(j);
DT.Rows[i][j] = sh.GetRow(i).GetCell(j);
}
i++;
}
return DT;
}
Plese hlp me.
you may have to try something along this line. its workable code to read the excel using NPOI.
// read the current row data
XSSFRow headerRow = (XSSFRow)sheet.GetRow(0);
// LastCellNum is the number of cells of current rows
int cellCount = headerRow.LastCellNum;
// LastRowNum is the number of rows of current table
int rowCount = sheet.LastRowNum + 1;
bool isBlanKRow = false;
//Start reading data after first row(header row) of excel sheet.
for (int i = (sheet.FirstRowNum + 1); i < rowCount; i++)
{
XSSFRow row = (XSSFRow)sheet.GetRow(i);
DataRow dataRow = dt.NewRow();
isBlanKRow = true;
try
{
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (null != row.GetCell(j) && !string.IsNullOrEmpty(row.GetCell(j).ToString()) && !string.IsNullOrWhiteSpace(row.GetCell(j).ToString()))
{
dataRow[j] = row.GetCell(j).ToString();
isBlanKRow = false;
}
}
}
catch (Exception Ex)
{
}
if (!isBlanKRow)
{
dt.Rows.Add(dataRow);
}
}

Create an Excel file with the Excel interop class from SQL Database

I want to create an Excel file with the Excel interop class from the SQL Database. With SQL query, I had previously transferred the dataset into dataGridview. The result of the query is the data. However, I can't Print this data from the SQL database to Excel cells with the dataset.
private void linkLabel10_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
string fileTest = fbd.SelectedPath.ToString() + "\\"+ comboBox1.Text.Substring(0, comboBox1.Text.IndexOf("*") - 1) +"-"+ comboBox2.Text.Substring(0, comboBox2.Text.IndexOf("(") - 1) +"-"+ comboBox2.Text.Substring(comboBox2.Text.IndexOf("(") + 1, 10) + ".xlsx";
MessageBox.Show(fileTest);
if (File.Exists(fileTest))
{
File.Delete(fileTest);
}
SqlDataAdapter da = new SqlDataAdapter("select PersonelKodu= ztSinifEgitimiDurum.KisiID, İsim= dbo.cdCurrAcc.FullName, Katılım = CASE WHEN Katilim = 1 THEN 'Katıldı' ELSE 'Katılmadı' END, ztSinifEgitimiDurum.ID FROM dbo.ztSinifEgitimiDurum INNER JOIN dbo.cdCurrAcc ON cdCurrAcc.CurrAccCode = ztSinifEgitimiDurum.KisiID AND cdCurrAcc.CurrAccTypeCode = ztSinifEgitimiDurum.KisiTipiID WHERE AtamaID =" + AtamaIDBul(), baglan);
DataSet ds = new DataSet();
Excel.Application Excel;
Excel.Worksheet excelWorkSheet;
Excel.Workbook excelWorkBook;
Excel = new Excel.Application();
excelWorkBook = Excel.Workbooks.Add();
excelWorkSheet = (Excel.Worksheet)excelWorkBook.Worksheets.get_Item(1);
excelWorkSheet.Cells[1, 1] = "some value";
excelWorkSheet.Name = "Ali";
foreach (DataTable table in ds.Tables)
{
for (int i = 1; i < table.Columns.Count + 1; i++)
{
excelWorkSheet.Cells[1, i] = table.Columns[i - 1].ColumnName;
MessageBox.Show(table.Columns[i - 1].ColumnName.ToString());
}
for (int j = 0; j < table.Rows.Count; j++)
{
for (int k = 0; k < table.Columns.Count; k++)
{
excelWorkSheet.Cells[j + 2, k + 1] = table.Rows[j].ItemArray[k].ToString();
}
}
}
// excelWorkSheet.Cells[1, 1] = "some value";
excelWorkBook.SaveAs(fileTest);
excelWorkBook.Close();
Excel.Quit();
}
}
}
You forgot to fill your DataSet, add this line
da.Fill(ds); after DataSet ds = new DataSet();
You can try this code to fill your sheet with values from a table:
ws.Activate();
foreach (DataTable dt in ds.Tables)
{
// Add column headers from the datatable
for (int Idx = 0; Idx < dt.Columns.Count; Idx++)
{
ws.Range["A1"].Offset[0, Idx].Value = dt.Columns[Idx].ColumnName;
}
// add data rows
for (int Idx = 0; Idx < dt.Rows.Count; Idx++)
{ // hey I did not invent this line of code, I found it somewhere on CodeProject.
// It works to add the whole row at once
ws.Range["A2"].Offset[Idx].Resize[1, dt.Columns.Count].Value = dt.Rows[Idx].ItemArray;
}
...
But you will have to add more worksheets for individual tables in case there is more than one table in your DataSet.
It is based on this article.

How to copy data from one column to another at the same datatable in c#

I have a datatable filled with information from an excel file. I have more than four columns but to bring an example I'm writing just four of them. I have to write a program in which if the value of the cell in the column C is 0, then I have to copy column B to column A. If the value of the cell in column C is > 0 then i have to copy the column B to A and should add another row in which i have to copy the value of the column C to A.
What i have till now is
for (int r = 2; r <= ws.UsedRange.Rows.Count; r++)
{ if (ws.UsedRange.Cells[r, 3].Text == "0")
{
DataRow row = dt.NewRow();
for (int c = 1; c < ws.UsedRange.Columns.Count; c++)
{
string cell = ws.Cells[r, c].Text;
row[c - 1] = cell;
}
}
So my questions are:
How can i copy a column to another in the same datatable? Copy B to A.
How can i add another row and copy the value of C to A only for that row?
Here is the full code:
public DataTable ReadExcel2(string file)
{
ExcelI.Application app = new ExcelI.Application(); //create an excel instance
ExcelI.Workbook wb = app.Workbooks.Open(file, ReadOnly: true); //open a file
ExcelI.Worksheet ws = wb.Worksheets[1]; //choose a sheet. The firt one
var rng = ws.UsedRange;
//takes the index of the columns that are going to be filtered
int service = ColumnIndexByName(ws.Cells[1, 1].EntireRow, "Service");
int status = ColumnIndexByName(ws.Cells[1, 1].EntireRow, "Status");
int code = ColumnIndexByName(ws.Cells[1, 1].EntireRow, "Code");
DataTable dt = new DataTable();
dt.Columns.Add("A", typeof(string));
for (int c = 1; c < ws.UsedRange.Columns.Count; c++)
{
string colName = ws.Cells[1, c].Text;
int i = 2;
while (dt.Columns.Contains(colName))
{
colName = ws.Cells[1, c].Text + "{" + i.ToString() + "}";
i++;
}
dt.Columns.Add(colName);
}
//do a loop to delete the rows that we dont need
for (int r = 2; r <= ws.UsedRange.Rows.Count; r++)
{
if (ws.UsedRange.Cells[r, 3].Text == "0")
{
DataRow row = dt.NewRow();
for (int c = 1; c < ws.UsedRange.Columns.Count; c++)
{
string cell = ws.Cells[r, c].Text;
row[c - 1] = cell;
}
dt.Rows.Add(row);
row["A"] = row["C"];
}
}
//Close the file
wb.Close();
//release the excel objects from use
Marshal.ReleaseComObject(wb);
Marshal.ReleaseComObject(ws);
//take the id of excel process
int pid = app.PID();
app.Quit();
StartProc("taskkill", $"/f /pid {pid}");
return dt;
}
To add row use dt.Rows.Add(row);, about "copy the column B to A" you mean copy value , just assign row[0] = row[2];, by the way , your example missing a bracket.
I think you should review your code according to conditions in your question, and you can do it yourself as well. Just pay attention to condition you wrote in question and conditional operator you checked in the code.

How to solve Unable to cast object of type 'System.Data.DataView' to type 'System.Data.DataTable' ERROR

i have Devxpress GridControl on the form,
and i want to send data on this grid to excel.
and i dont want to do this with ExportToExcel method
i have googled and found this code
but this code is for DataGrid control of .Net
and it gives an error when it tries to convert
DevExpress.XtraGrid.Views.Grid.GridView to System.Data.DataView
here is the code
public string LastCoulmLetter(int coulmnCount)
{
string finalColLetter = string.Empty;
string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int colCharsetLen = colCharset.Length;
if (coulmnCount > colCharsetLen)
{
finalColLetter = colCharset.Substring(
(coulmnCount - 1) / colCharsetLen - 1, 1);
}
finalColLetter += colCharset.Substring(
(coulmnCount - 1) % colCharsetLen, 1);
return finalColLetter;
}
public void FromGridToExcel()
{
if (gridView1.RowCount <= 0)
return;
Excel.Application xls = new Excel.Application();
Excel.Workbook wb;
Excel.Worksheet sheet;
object SalakObje = System.Reflection.Missing.Value;
wb = xls.Workbooks.Add(SalakObje);
sheet = (Excel.Worksheet)wb.ActiveSheet;
sheet.Name = "Result";
xls.Visible = true;
DataTable dt = (DataTable)gridView1.DataSource; // Error comes in here
// Copy the DataTable to an object array
object[,] rawData = new object[dt.Rows.Count + 1, dt.Columns.Count];
// Copy the column names to the first row of the object array
for (int col = 0; col < dt.Columns.Count; col++)
{
rawData[0, col] = dt.Columns[col].ColumnName;
}
// Copy the values to the object array
for (int col = 0; col < dt.Columns.Count; col++)
{
for (int row = 0; row < dt.Rows.Count; row++)
{
rawData[row + 1, col] = dt.Rows[row].ItemArray[col];
}
}
// Fast data export to Excel
string excelRange = string.Format("A1:{0}{1}",LastCoulmLetter(dt.Columns.Count), dt.Rows.Count + 1);
sheet.get_Range(excelRange, Type.Missing).Value2 = rawData;
sheet.get_Range(excelRange).Columns.AutoFit();
}
So what is the problem and how to fix it
The problem appears to be that your DataSource is a DataView, not a DataTable.
Some options:
Cast it to a DataView if you want to use the same filters:
DataView dv = (DataView)gridView1.DataSource;
Use the .Table property to get the source table if you want the raw data:
DataTable dt = ((DataView)gridView1.DataSource).Table;
Try this instead:
DataTable dt = ((DataView)gridView1.DataSource).Table;

Categories