I copy the data from one location to another and am able to read and print all values. But not able to append the column in the Excel file. I need to Append three columns in the beginning (Ex: 'A').
private void btnUpload_Click(object sender, RoutedEventArgs e)
{
ApplicationClass app = new ApplicationClass();
Workbook book = null;
Worksheet sheet = null;
Range range = null;
try
{
app.Visible = false;
app.ScreenUpdating = false;
app.DisplayAlerts = false;
book = app.Workbooks.Open(#"C:\Windows\Temp\" + FileName, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value);
sheet = (Worksheet)book.Worksheets[1];
// get a range to work with
range = sheet.get_Range("A1", Missing.Value);
// get the end of values to the right (will stop at the first empty cell)
range = range.get_End(XlDirection.xlToRight);
// get the end of values toward the bottom, looking in the last column (will stop at first empty cell)
range = range.get_End(XlDirection.xlDown);
// get the address of the bottom, right cell
string downAddress = range.get_Address(
false, false, XlReferenceStyle.xlA1,
Type.Missing, Type.Missing);
// Get the range, then values from a1
range = sheet.get_Range("A1", downAddress);
object[,] values = (object[,])range.Value2;
// Value2 is a two dimenial array dime one = row, dime two = column.
Console.WriteLine("Col Count: " + values.GetLength(1).ToString());
Console.WriteLine("Row Count: " + values.GetLength(0).ToString());
Microsoft.Office.Interop.Excel.Range oRng = sheet.Range["A1"];
oRng.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight,
Microsoft.Office.Interop.Excel.XlInsertFormatOrigin.xlFormatFromRightOrBelow);
oRng = sheet.Range["A1"];
oRng.Value2 = "Discount";
Microsoft.Office.Interop.Excel.Range oRng = sheet.Range["B1"];
oRng.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight,
Microsoft.Office.Interop.Excel.XlInsertFormatOrigin.xlFormatFromRightOrBelow);
oRng = sheet.Range["B1"];
oRng.Value2 = "NOTHING";
Microsoft.Office.Interop.Excel.Range oRng = sheet.Range["C1"];
oRng.EntireColumn.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftToRight,
Microsoft.Office.Interop.Excel.XlInsertFormatOrigin.xlFormatFromRightOrBelow);
oRng = sheet.Range["C1"];
oRng.Value2 = "HELLO";
}
catch (Exception k)
{
Console.WriteLine(k);
}
finally
{
range = null;
sheet = null;
if (book != null)
book.Close(false, Missing.Value, Missing.Value);
book = null;
if (app != null)
app.Quit();
app = null;
MessageBox.Show("File Uploaded Successfully. Please Wait...!");
}
}
You only need to set the value of the cell. Don't use "A1" as cell because you need the column number: A is the first letter, so it needs to be column 1 and B is the second letter, needs to be column 2 etc. In the following code you can see how to do it correctly:
Excel.Application app = new Excel.Application();
Excel.Workbooks workbooks = app.Workbooks;
string filename = #"yourFilename";
workbooks.Open(filename);
Excel.Workbook workbook = workbooks.Item[1];
Excel.Sheets worksheets = workbook.Worksheets;
Excel.Worksheet worksheet = worksheets.Item[1];
Excel.Range cells = worksheet.UsedRange;
cells[1, 2] = "Hello";//Set value for row 1 and column 2 (A1)
cells[1, 3] = "World";//Set value for row 1 and column 3 (B1)
workbook.Save();//Save Excel-File
app.Quit();
Console.ReadKey();
Related
I have a C# web form, that a user enters a part numbers and a quantity on, then selects a button. Ideally, I want to search the excel file for the part that was entered, then add the quantity specified by the user.
The excel file is a static list of all parts that can be entered. I'm just testing the code, so for testing I'm just changing the color of the text and making it bold if its found...
Now, I'm getting the error...
"'HttpApplicationState' does not contain a definition for 'get_Range' and no extension method 'get_Range' accepting a first argument of type 'HttpApplicationState' could be found (are you missing a using directive or an assembly reference?) CSMP_Bid_Registration C:\BPR Projects\CSMP Registration\CSMP_Registration_1_03\CSMP_Bid_Registration\Create.aspx.cs 452 Active"
protected void btnSearchRequest_Click(object sender, EventArgs e)
{
//Microsoft.Office.Interop.Excel.Range currentFind = null;
Microsoft.Office.Interop.Excel.Range firstFind = null;
object False = false;
object True = true;
_Application excel = new Microsoft.Office.Interop.Excel.Application();
String _Created = DateTime.Now.ToString("MM-dd-yy");
string _reportName = " CSMP Pricing Workbook " + CustomerLookup.CustomerName + " " + _Created + ".xlsm";
string fileName = "C:\\BPR Projects\\CSMP Registration\\CSMP_Registration_1_03\\CSMP_Bid_Registration\\UploadedFiles\\CSMP.xlsx";
Microsoft.Office.Interop.Excel.Workbook wb = excel.Workbooks._Open(#fileName, False, False, Missing.Value, Missing.Value, False, False, Missing.Value, Missing.Value, False, Missing.Value, Missing.Value, True);
Aspose.Cells.Workbook _book = new Aspose.Cells.Workbook(fileName);
//Aspose.Cells.Worksheet _sheet = _book.Worksheets[2];
_Worksheet ws = (_Worksheet)wb.Worksheets[2];
string from = "A1";
string to = "A999";
Range rng = ws.get_Range(from, to);
Range currentFind = rng.Find("8460B001AA", Missing.Value, XlFindLookIn.xlValues, Missing.Value, Missing.Value, XlSearchDirection.xlNext, False, False, Missing.Value);
currentFind.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
currentFind.Font.Bold = true;
currentFind = currentFind.FindNext(currentFind);
while (currentFind != null)
{
Keep track of the first range you find.
if (currentFind == null)
{
currentFind = currentFind;
}
// If you didn't move to a new range, you are done.
else if (currentFind.get_Address(Microsoft.Office.Interop.Excel.XlReferenceStyle.xlA1)
== currentFind.get_Address(Microsoft.Office.Interop.Excel.XlReferenceStyle.xlA1))
{
break;
}
currentFind.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
currentFind.Font.Bold = true;
currentFind = currentFind.FindNext(currentFind);
}
_book.Save(HttpContext.Current.Response, _reportName, Aspose.Cells.ContentDisposition.Attachment, new Aspose.Cells.XlsSaveOptions(Aspose.Cells.SaveFormat.Xlsm));
}
When I export a data table to excel how can I identify how many rows are inserted to Excel, and get the next row position of the same Excel sheet to insert the next data table values?
var lines = new List<string>();
string[] columnNames = dataTable.Columns.Cast<DataColumn>().
Select(column => column.ColumnName).
ToArray();
var header = string.Join(",", columnNames);
lines.Add(header);
var valueLines = dataTable.AsEnumerable()
.Select(row => string.Join(",", row.ItemArray));
lines.AddRange(valueLines);
File.WriteAllLines("excel.csv",lines);
private static Microsoft.Office.Interop.Excel.Workbook mWorkBook;
private static Microsoft.Office.Interop.Excel.Sheets mWorkSheets;
private static Microsoft.Office.Interop.Excel.Worksheet mWSheet1;
private static Microsoft.Office.Interop.Excel.Application oXL;
public static void ReadExistingExcel()
{
string path = #"C:\Tool\Reports1.xls";
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get all the sheets in the workbook
mWorkSheets = mWorkBook.Worksheets;
//Get the allready exists sheet
mWSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)mWorkSheets.get_Item("Sheet1");
Microsoft.Office.Interop.Excel.Range range= mWSheet1.UsedRange;
int colCount = range.Columns.Count;
int rowCount= range.Rows.Count;
for (int index = 1; index < 15; index++)
{
mWSheet1.Cells[rowCount + index, 1] = rowCount +index;
mWSheet1.Cells[rowCount + index, 2] = "New Item"+index;
}
mWorkBook.SaveAs(path, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
mWorkBook.Close(Missing.Value, Missing.Value, Missing.Value);
mWSheet1 = null;
mWorkBook = null;
oXL.Quit();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
I have a Gridview which i fill with a Datatable. On the webpage the user has to be able to download an excel file with the contents of the Gridview. So mi thought the easiest way to save the files is to save the datatable as an excel file. I have troied this method, which i found here on stackoverflow.
using Excel = Microsoft.Office.Interop.Excel;
public static bool ExportDataTableToExcel(DataTable dt, string filepath)
{
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 = true;
oXL.DisplayAlerts = false;
// Get a new workbook.
oWB = oXL.Workbooks.Add(Missing.Value);
// Get the Active sheet
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
oSheet.Name = "Data";
int rowCount = 1;
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
// Add the header the first time through
if (rowCount == 2)
{
oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
}
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;
oWB.SaveAs(filepath, Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
oWB.Close(Missing.Value, Missing.Value, Missing.Value);
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;
}
Bu i get a build error stating that "The name Missing does not exist in the current context" and i cant seem to figure out why? can anyone help ?
the code is pasted from this stackoverflow page here
According to msdn here, Missing.Value is defined in System.Reflection. You should add a reference to this namespace.
using System.Reflection;
I want to export data from Dataset or Data Table to Excel file in C# without using Gridview.
I would recommend EPPlus - this solution doesn't require COM nor interop dlls and is very fast. Perfectly suited for web scenarios.
http://epplus.codeplex.com/
http://nuget.org/packages/EPPlus
private void DumpExcel(DataTable tbl)
{
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
//Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
ws.Cells["A1"].LoadFromDataTable(tbl, true);
//Format the header for column 1-3
using (ExcelRange rng = ws.Cells["A1:C1"])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189)); //Set color to dark blue
rng.Style.Font.Color.SetColor(Color.White);
}
//Example how to Format Column 1 as numeric
using (ExcelRange col = ws.Cells[2, 1, 2 + tbl.Rows.Count, 1])
{
col.Style.Numberformat.Format = "#,##0.00";
col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
}
//Write it back to the client
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
}
}
}
}
Get more ways : 9 Solutions to Export Data to Excel for ASP.NET
I have this code but for this you need to include Excel Com Component
Add reference of Microsoft.Office.Interop.Excel.dll in your project will do task for you.
using Excel = Microsoft.Office.Interop.Excel;
public static bool ExportDataTableToExcel(DataTable dt, string filepath)
{
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 = true;
oXL.DisplayAlerts = false;
// Get a new workbook.
oWB = oXL.Workbooks.Add(Missing.Value);
// Get the Active sheet
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
oSheet.Name = "Data";
int rowCount = 1;
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
// Add the header the first time through
if (rowCount == 2)
{
oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
}
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;
oWB.SaveAs(filepath, Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
oWB.Close(Missing.Value, Missing.Value, Missing.Value);
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;
}
you can use
using Microsoft.Office.Interop.Excel;
to work with excel documents "native"...
Using C# to Create an Excel Document
http://www.codeproject.com/Articles/20228/Using-C-to-Create-an-Excel-Document
But most of the common report Generator/Designers can easily export to excel
also check for Reporting Services if you are using SQL SERVER
Just in case somebody else used the chosen solution and run into the "object does not contain a definition for get_Range" exception. I found the solution here: Worksheet get_Range throws exception. I hope this will save your time.
I am trying to open an Excel file and populate its cells with data? I have done the following coding so far.
Currently I am at this stage with the following code but still I am getting errors:
Microsoft.Office.Interop.Excel.ApplicationClass appExcel =
new Microsoft.Office.Interop.Excel.ApplicationClass();
try
{
// is there already such a file ?
if (System.IO.File.Exists("C:\\csharp\\errorreport1.xls"))
{
// then go and load this into excel
Microsoft.Office.Interop.Excel.Workbooks.Open(
"C:\\csharp\\errorreport1.xls", true, false,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value);
}
else
{
// if not go and create a workbook:
newWorkbook = appExcel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel._Worksheet excelWorksheet =
(Microsoft.Office.Interop.Excel._Worksheet)
newWorkBook.Worksheets.get_Item(1);
}
i++;
j = 1;
j++;
objsheet.Cells(i, j).Value = "Tabelle: " + rs.Fields["Table_Name"];
j++;
objsheet.Cells(i, j).Value = "kombinationsschluessel:FALL "
+ rs3.Fields[1].Value;
j++;
objsheet.Cells(i, j).Value = "Null Value: ";
j++;
objsheet.Cells(i, j).Value = "Updated with 888";
These are the top 2 errors I am getting:
Error 1 An object reference is required for the nonstatic field, method, or
property 'Microsoft.Office.Interop.Excel.Workbooks.Open(string, object,
object, object, object, object, object, object, object, object, object,
object, object, object, object)'
Error 2 The name 'newWorkbook' does not exist in the current context
If you are trying to automate Excel, you probably shouldn't be opening a Word document and using the Word automation ;)
Check this out, it should get you started,
http://www.codeproject.com/KB/office/package.aspx
And here is some code. It is taken from some of my code and has a lot of stuff deleted, so it doesn't do anything and may not compile or work exactly, but it should get you going. It is oriented toward reading, but should point you in the right direction.
Microsoft.Office.Interop.Excel.Worksheet sheet = newWorkbook.ActiveSheet;
if ( sheet != null )
{
Microsoft.Office.Interop.Excel.Range range = sheet.UsedRange;
if ( range != null )
{
int nRows = usedRange.Rows.Count;
int nCols = usedRange.Columns.Count;
foreach ( Microsoft.Office.Interop.Excel.Range row in usedRange.Rows )
{
string value = row.Cells[0].FormattedValue as string;
}
}
}
You can also do
Microsoft.Office.Interop.Excel.Sheets sheets = newWorkbook.ExcelSheets;
if ( sheets != null )
{
foreach ( Microsoft.Office.Interop.Excel.Worksheet sheet in sheets )
{
// Do Stuff
}
}
And if you need to insert rows/columns
// Inserts a new row at the beginning of the sheet
Microsoft.Office.Interop.Excel.Range a1 = sheet.get_Range( "A1", Type.Missing );
a1.EntireRow.Insert( Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, Type.Missing );
I think, that you have to declare the associated sheet!
Try something like this
objsheet(1).Cells[i,j].Value;
How I work to automate Office / Excel:
Record a macro, this will generate a VBA template
Edit the VBA template so it will match my needs
Convert to VB.Net (A small step for men)
Leave it in VB.Net, Much more easy as doing it using C#
Try:
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;
oXL = new Excel.Application();
oXL.Visible = true;
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Excel._Worksheet)oWB.Worksheets;
oSheet.Activate();
oSheet.Cells[3, 9] = "Some Text"
Simple.
To open a workbook.
Use xlapp.workbooks.Open()
where you have previously declared and instanitated xlapp as so..
Excel.Application xlapp = new Excel.Applicaton();
parameters are correct.
Next make sure you use the property Value2 when assigning a value to the cell using either the cells property or the range object.
This works fine for me
Excel.Application oXL = null;
Excel._Workbook oWB = null;
Excel._Worksheet oSheet = null;
try
{
oXL = new Excel.Application();
string path = #"C:\Templates\NCRepTemplate.xlt";
oWB = oXL.Workbooks.Open(path, 0, false, 5, "", "",
false, Excel.XlPlatform.xlWindows, "", true, false,
0, true, false, false);
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
oSheet.Cells[2, 2] = "Text";
You can use the below code; it's working fine for me:
newWorkbook = appExcel.Workbooks.Add();