I want to create excel from datatable, And want to create maximum 25 sheets(each day for current month excluding weekend, Saturday,Sunday and bank holiday) , how can we do this by taking string of array for total days in month and datatable.
Public static void CreateExcel_TabNameUnique( DataTable dt1,string ExcelFilePath, string Tab_Name1)
{
try
{
runDate = DateTime.Today;
currMonth = DateTime.Today;
object missing = Type.Missing;
Excel.Application oXL = new Excel.Application();
oXL.Visible = false;
Excel.Workbook oWB = oXL.Workbooks.Add(missing);
Excel.Worksheet oSheet = oWB.ActiveSheet as Excel.Worksheet;
oSheet.Name = Tab_Name1;
// column headings
for (int i = 0; i < dt1.Columns.Count; i++)
{
oSheet.Cells[1, (i + 1)] = dt1.Columns[i].ColumnName;
}
// rows
for (int i = 0; i < dt1.Rows.Count; i++)
{
for (int j = 0; j < dt1.Columns.Count; j++)
{
oSheet.Cells[(i + 2), (j + 1)] = dt1.Rows[i][j];
}
}
if (ExcelFilePath != null && ExcelFilePath != "")
{
try
{
oWB.SaveAs(ExcelFilePath, Excel.XlFileFormat.xlOpenXMLWorkbook,
missing, missing, missing, missing,
Excel.XlSaveAsAccessMode.xlNoChange,
missing, missing, missing, missing, missing);
oWB.Close(missing, missing, missing);
oXL.UserControl = true;
oXL.Quit();
}
catch (Exception ex)
{
}
}
}
catch (Exception ex)
{
}
}
Sorry for not being able to verify this at the moment (problems with Excel Interop...), but from your comment I take it your problem is just in adding a second worksheet. You should be able to do this with:
Excel.Worksheet secondWorkSheet = oWB.Worksheets.Add();
Then proceed to manipulate worksheet as you are doing in the code you posted.
Related
I am facing an issue regarding excel writing .Below is the problem -
I have a requirement for which I have multiple excel sheets and for each excel file there could be multiple sheets .So, I need to write in a single excel with multiple individual sheets
ex- Lets say I have 3 excel file File1.xlsx with Sheet1, File2.xlsx with Sheet2 and File 3 with multiple sheet Sheet3 and Sheet4.In each sheet the data is similar like 3 Columns (Name,EmployeeID,MobNo) So, the output would be Individual file Result.xlsx with multiple sheets Sheet1,Sheet2,Sheet3 & Sheet4.
Please share the code without any third party tools like Spire.xl.I need to do this programatically.Below is the code -
string inputPathFirstExcel =
#"C:\MyData\ExcelWritingApp\File1.xlsx";
string inputPathSecondExcel = #"C:\\ExcelWritingApp\File2.xlsx";
string[] ColumnData = { };
Excel.Application xlApp = null;
Excel.Workbook xlWorkBook = null;
Excel.Worksheet xlWorkSheet = null;
Excel.Range xlrange = null;
xlApp = new Excel.Application();
xlApp.Visible = false;
xlWorkBook = xlApp.Workbooks.Open(inputPathFirstExcel);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets[1];
xlrange = xlWorkSheet.UsedRange;
object missing = Type.Missing;
Excel.Application oXL = new Excel.Application();
oXL.Visible = false;
Excel.Workbook oWB = oXL.Workbooks.Add(missing);
Excel.Worksheet oSheet = oWB.ActiveSheet as Excel.Worksheet;
oSheet.Name = "Sheet1";
Microsoft.Office.Interop.Excel.Range xlRange = xlWorkSheet.UsedRange;
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Employee");
dt.Columns.Add("MobNo");
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
for (int i = 1; i <= colCount; i++)
{
oSheet.Cells[1, i] = dt.Columns[i - 1].ToString().ToUpper() + "\t";
}
for (int i = 0; i < rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
oSheet.Cells[i + 2, j] = Convert.ToString((xlRange.Cells[i + 2, j] as Excel.Range).Value2);
}
}
string fileName = #"C:\Result.xlsx";
oWB.SaveAs(fileName, Excel.XlFileFormat.xlOpenXMLWorkbook,
missing, missing, missing, missing,
Excel.XlSaveAsAccessMode.xlNoChange,
missing, missing, missing, missing, missing);
i am using Interop.Excel to export data from datatable and generate line chart too.
i could successfully export data to excel from data like this way
public static bool Export(System.Data.DataTable dt, string sheetName)
{
object Missing = System.Reflection.Missing.Value;
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
Excel.Range oRange;
try
{
// Start Excel and get Application object.
oXL = new Excel.Application();
// Set some properties
oXL.Visible = false;
oXL.DisplayAlerts = false;
// Get a new workbook.
oWB = oXL.Workbooks.Add(Missing);
// Get the Active sheet
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
oSheet.Name = sheetName;
oSheet.Cells[1, 1] = "Daily Finished Job History " + DateTime.Now.ToString("dd/MM/yyyy");
oSheet.get_Range("A1", "A1").ColumnWidth = 13;
oSheet.get_Range("B1", "B1").ColumnWidth = 13;
oSheet.get_Range("C1", "C1").ColumnWidth = 25;
oSheet.get_Range("A1", "C1").Font.Size = 14;
oSheet.get_Range("A1", "C1").Font.Bold = true;
oSheet.get_Range("A1", "C1").Merge(true);
oSheet.get_Range("A1", "C1").Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
oSheet.get_Range("A3", "C3").Font.Bold = true;
int rowCount = 3;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
oSheet.Cells[rowCount, i] = dt.Columns[i - 1].ColumnName;
}
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
// Resize the columns
oRange = oSheet.get_Range(oSheet.Cells[1, 1],
oSheet.Cells[rowCount, dt.Columns.Count]);
//oRange.EntireColumn.AutoFit();
// Save the sheet and close
oSheet = null;
oRange = null;
string strParentDirectory = GetParentDirectory();
strParentDirectory = strParentDirectory + "\\Data";
if (!Directory.Exists(strParentDirectory))
{
Directory.CreateDirectory(strParentDirectory);
}
string strFileName = strParentDirectory + "\\DailyFinishedJobHistory_" + DateTime.Now.ToString("yyyyMMdd") + ".xls";
if (File.Exists(strFileName))
{
File.Delete(strFileName);
}
FileStream file = new FileStream(strFileName, FileMode.Create);
file.Close();
oWB.SaveAs(strFileName, Excel.XlFileFormat.xlWorkbookNormal,
Missing, Missing, Missing, Missing,
Excel.XlSaveAsAccessMode.xlExclusive,
Missing, Missing, Missing,
Missing, Missing);
oWB.Close(Missing, Missing, Missing);
oWB = null;
oXL.Quit();
}
catch
{
throw;
}
finally
{
// Clean up
// NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
return true;
}
public static string GetParentDirectory()
{
System.IO.DirectoryInfo myDirectory = new DirectoryInfo(Environment.CurrentDirectory);
return myDirectory.Parent.Parent.FullName;
}
now i want to generate chart in same sheet based on data from my datatable.
my excel file would look like as follows
i read few article & code to generate chart from this links
http://www.dotnetbull.com/2011/09/exporting-pie-chart-into-excel-file.html
http://csharp.net-informations.com/excel/csharp-excel-chart.htm
http://www.daniweb.com/software-development/csharp/threads/80834/c-and-excel-chart-ranges
but still not being able to understand the code to generate line chart. it would be great help if some help me to generate chart in same sheet like the image i have given here.
thanks
Try this as a starting point:
'Create & Format Chart
Dim oChart As Excel.Chart
oChart = oXL.Parent.Charts.Add
With oChart
.Name = "History"
.HasTitle = True
.ChartTitle.Font.ColorIndex = 11
.ChartTitle.Font.Bold = True
.ChartTitle.Font.Size = 12
.ChartTitle.Font.Name = "Arial"
.ChartTitle.Text = "Job History"
.ChartType = Excel.XlChartType.xlLine
.HasLegend = True
.SeriesCollection(1).XValues = "=Sheet1!$A$4:$A$6"
.SeriesCollection(1).Name = "=Sheet1!$B$3"
.SeriesCollection(2).Name = "=Sheet1!$C$3"
.SeriesCollection(3).Name = "=Sheet1!$D$3"
End With
i am working on excel import to grid view using DataTable in c#, but my problem is its working fine on my local system but its redirecting to login page on my online server and i have tried both Microsoft.Office.Interop.Excel & OLEdb connection. but the problem is same. please tell me what is the problem with these or any one have any other function to import Excel data in GridView.
private void processExcel(string filename)
{
filename = Server.MapPath("~/Files/WM-0b23-productsBook.xlsx");
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
var missing = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(filename, false, true, missing, missing, missing, true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, '\t', false, false, 0, false, true, 0);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Microsoft.Office.Interop.Excel.Range xlRange = xlWorkSheet.UsedRange;
Array myValues = (Array)xlRange.Cells.Value2;
int vertical = myValues.GetLength(0);
int horizontal = myValues.GetLength(1);
System.Data.DataTable dt = new System.Data.DataTable();
// must start with index = 1
// get header information
for (int i = 1; i <= horizontal; i++)
{
dt.Columns.Add(new DataColumn(myValues.GetValue(1, i).ToString()));
}
// Get the row information
for (int a = 2; a <= vertical; a++)
{
object[] poop = new object[horizontal];
for (int b = 1; b <= horizontal; b++)
{
poop[b - 1] = myValues.GetValue(a, b);
}
DataRow row = dt.NewRow();
row.ItemArray = poop;
dt.Rows.Add(row);
}
// assign table to default data grid view
GridView1.DataSource = dt;
GridView1.DataBind();
xlWorkBook.Close(true, missing, missing);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
Have a look:
private void processExcel(string filename)
{
filename = Server.MapPath("~/Files/WM-0b23-productsBook.xlsx");
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
var missing = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(filename, false, true, missing, missing, missing, true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, '\t', false, false, 0, false, true, 0);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Microsoft.Office.Interop.Excel.Range xlRange = xlWorkSheet.UsedRange;
Array myValues = (Array)xlRange.Cells.Value2;
int vertical = myValues.GetLength(0);
int horizontal = myValues.GetLength(1);
System.Data.DataTable dt = new System.Data.DataTable();
// must start with index = 1
// get header information
for (int i = 1; i <= horizontal; i++)
{
dt.Columns.Add(new DataColumn(myValues.GetValue(1, i).ToString()));
}
// Get the row information
for (int a = 2; a <= vertical; a++)
{
object[] poop = new object[horizontal];
for (int b = 1; b <= horizontal; b++)
{
poop[b - 1] = myValues.GetValue(a, b);
}
DataRow row = dt.NewRow();
row.ItemArray = poop;
dt.Rows.Add(row);
}
// assign table to default data grid view
GridView1.DataSource = dt;
GridView1.DataBind();
xlWorkBook.Close(true, missing, missing);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
It is better not using MS Office interop in server cases which will bring a lot of performance and memory issues in the future. Recommend using some 3rd party library, for example: https://www.nuget.org/packages/Spread.Services/ to get what you wanted.
how to read an excel file and change its column data type to string
right now i have an excel sheet with column no :10
the data there is been displayed like this
1/5/2010
6/12/2010
i need to change into this format "dd-MM-yyyy"
so that it displays like this.
01-05-2010
06-12-2010
can any one please tel me how to do this.
any help would be really great
it reads and update the excel file.before doing this do the following steps
1.Rightclick solution explorer,then select Add Reference
2.select Microsoft.Office.interop.Excel in .Net Tab
3. Add this line in your code (i.e) in the NameSpace:
using Excel = Microsoft.Office.Interop.Excel;
string address;
Excel.ApplicationClass excel = new Excel.ApplicationClass();
object Missing = Type.Missing;
FileInfo fInfo = new FileInfo(#"D:\Book1.xls");
if (fInfo.Exists)
{
Excel.Workbook workbook = excel.Workbooks.Open(#"D:\Book1.xls", Missing, Missing,
Missing, Missing, Missing, Missing, Missing,
Missing, Missing, Missing, Missing, Missing,
Missing, Missing);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets["Sheet1"];
Excel.Range docNumber = worksheet.Cells.Find("10/5/2010", worksheet.Cells[1, 1],
Excel.XlFindLookIn.xlValues,
Excel.XlLookAt.xlPart, Missing, Excel.XlSearchDirection.xlNext,
false, Missing, Missing);
if (docNumber != null)
{
address = docNumber.get_Address(true, true, Excel.XlReferenceStyle.xlA1, Missing,
Missing);
docNumber = worksheet.UsedRange;
DateTime parsedDate;
for (int rCnt = 1; rCnt <= docNumber.Rows.Count; rCnt++)
{
for (int cCnt = 1; cCnt <= docNumber.Columns.Count; cCnt++)
{
string str = (string)(docNumber.Cells[rCnt, cCnt] as Excel.Range).Text ;
parsedDate = DateTime.Parse(str);
str = String.Format("{0:dd-mm-yyyy}", parsedDate);
docNumber.Cells[rCnt, cCnt] = str;
}
}
workbook.Save();
}
}
In my Windows based application(C#)
i want to import excel sheet to show its data in DatatGridView
i dont want to use oledb
any Help
using Excel = Microsoft.Office.Interop.Excel;
You'll obviously need to add the reference to your project, and then it's plain simple :)
private void ProcessExcel(string filepath)
{
Excel.ApplicationClass ExcelObj = new Excel.ApplicationClass();
Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(filepath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Excel.Sheets sheets = theWorkbook.Worksheets;
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
Excel.Range range = worksheet.UsedRange;
System.Array myvalues = (System.Array)range.Cells.Value2;
int vertical = myvalues.GetLength(0);
int horizontal = myvalues.GetLength(1);
string[] headers = new string[horizontal];
string[] data = new string[horizontal];
DataTable ResultsHeader = New DataTable();
DataSet ds = New DataSet();
for (int x = 1; x <= vertical; x++)
{
Utils.inicializarArrays(datos);
for (int y = 1; y <= horizontal; y++)
{
if (x == 1)
{
headers[y - 1] = myvalues.GetValue(x, y).ToString();
}
else
{
string auxdata = "";
if (myvalues.GetValue(x, y) != null)
auxdata = myvalues.GetValue(x, y).ToString();
data[y - 1] = auxdata;
}
}
if(x == 1) //headers
{
for(int w = 0; w < horizontal; w++)
{
ResultsHeader.Columns.Add(New DataColumn(headers[w], GetType(string)));
}
ds.Tables.Add(ResultsHeader);
}
else
{
DataRow dataRow = ds.Tables[0].NewRow();
for(int w = 0; w < horizontal; w++)
{
dataRow(headers[w]) = data[w]
}
ds.Tables[0].Rows.Add(dataRow);
}
}
DataView myDataView = new DataView();
myDataView.Table = ds.Tables[0];
MydataGrid.CurrentPageIndex = 0;
MydataGrid.DataSource = myDataView;
MydataGrid.DataBind();
}
I'm late to the party, but I have something worthwhile to add! I tried Juan's code and it didn't compile out-of-the-box. I modified it a little bit after researching the internet for a few more hours and got it to do exactly what the original poster asked (as I needed to do the same thing). I had to piece code together from other sources, and unfortunately, I did not keep track of what bits and pieces I tried and changed so I can't comment much about it.
The following code works in Visual Studio 2008 with .NET 3.5. Also, the formatting is lost when the data is put into the array (for example, dates become doubles which require a conversion with DateTime.FromOADate() to change it back). The issue with that is you can't tell if a value is an actual double or a date from a coding viewpoint, but if you know ahead of time a column is going to be a date, then format it as you insert the data into the table.
private void processExcel(string filename)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
var missing = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open(filename, false, true, missing, missing, missing, true, Excel.XlPlatform.xlWindows, '\t', false, false, 0, false, true, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range xlRange = xlWorkSheet.UsedRange;
Array myValues = (Array)xlRange.Cells.Value2;
int vertical = myValues.GetLength(0);
int horizontal = myValues.GetLength(1);
DataTable dt = new DataTable();
// must start with index = 1
// get header information
for (int i = 1; i <= horizontal; i++)
{
dt.Columns.Add(new DataColumn(myValues.GetValue(1,i).ToString()));
}
// Get the row information
for (int a = 2; a <= vertical; a++)
{
object[] poop = new object[horizontal];
for (int b = 1; b <= horizontal; b++)
{
poop[b - 1] = myValues.GetValue(a, b);
}
DataRow row = dt.NewRow();
row.ItemArray = poop;
dt.Rows.Add(row);
}
// assign table to default data grid view
dataGridView1.DataSource = dt;
xlWorkBook.Close(true, missing, missing);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
Those codes above does not work.
That code works for me (.NET Framework 4.7.1)
private void processExcel(string filename)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
var missing = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(filename, false, true, missing, missing, missing, true, Excel.XlPlatform.xlWindows, '\t', false, false, 0, false, true, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range xlRange = xlWorkSheet.UsedRange;
Array myValues = (Array)xlRange.Cells.Value2;
int vertical = myValues.GetLength(0);
int horizontal = myValues.GetLength(1);
DataTable dt = new DataTable();
// must start with index = 1
// get header information
try
{
for (int i = 1; i <= horizontal; i++)
{
dt.Columns.Add(new DataColumn(Convert.ToString(myValues.GetValue(1, i))));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
// Get the row information
for (int a = 2; a <= vertical; a++)
{
object[] rows = new object[horizontal];
for (int b = 1; b <= horizontal; b++)
{
rows[b - 1] = myValues.GetValue(a, b);
}
DataRow row = dt.NewRow();
row.ItemArray = rows;
dt.Rows.Add(row);
}
// assign table to default data grid view
dataGridView1.DataSource = dt;
xlWorkBook.Close(true, missing, missing);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}