Exporting to excel with carriage returns - c#

I am trying to export to excel from my Datagrid. The Datagrid has a column where we put comments in. In that column the comments are put on separate lines. When it exports to excel it exports in multiple rows.
Here is how it looks in my DataGrid:
Here is how it looks when I export to Excel:
Here is the code that I am using to do it:
public static void CreateExcelFromClipboard(string worksheetName, string fullFilePath, bool toOpen)
{
//Excel Application class
_Application app = new Microsoft.Office.Interop.Excel.Application();
//Get process id
int excelProcessId = GetApplicationProcessId(app);
try
{
//Add workbook
Workbook theWorkbook = app.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
//Add worksheet
var theWorksheet =
(Worksheet)theWorkbook.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
theWorksheet.Name = worksheetName;
app.SheetsInNewWorkbook = 1;
app.DisplayAlerts = false;
theWorksheet.Activate();
//Paste to the worksheet from clpboard
theWorksheet.Paste(Type.Missing, Type.Missing);
//Apply Borders
ApplyBorder(theWorksheet.UsedRange);
//Auto Fit All columns
Range xlRange = theWorksheet.UsedRange;
// put all hardcodes in a constant class
xlRange.Font.Name = "Arial";
xlRange.Font.Size = 9;
var firstRowRange = (Range)xlRange.Rows[1, Missing.Value];
firstRowRange.EntireRow.Font.Bold = true;
firstRowRange.EntireRow.HorizontalAlignment = XlHAlign.xlHAlignCenter;
//Set Wrap Test to false
xlRange.WrapText = true;
xlRange.Columns.AutoFit();
theWorksheet.Activate();
//Save the file
theWorkbook.SaveAs(fullFilePath, XlFileFormat.xlOpenXMLWorkbook, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
if (!toOpen)
{
//Clean up
app.Quit();
Marshal.ReleaseComObject(app);
}
}
catch
{
ForceExcelClose(excelProcessId);
throw;
}
finally
{
app.Visible = toOpen;
}
}

Related

Searching multiple sheets in an excel C#

The code here grabs a name in my listbox(employeebox) and deletes the entire row on that sheet. This works and there are no errors.. My problem is that I have 19 different sheets that need to be checked, but I can only check 1 at a time with this code.. "Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[2];".. Is there any way that I can check all the sheets once the Delete button is clicked? I greatly appreciate anyone's help.
private void delete_Click(object sender, EventArgs e)
{
//create excel
Excel.Application xlexcel = new Excel.Application();
Excel.Workbook xlWorkBook = xlexcel.Workbooks.Open(#"C:\\SAMPLE.xlsx");
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[2];
//search within excel
Excel.Range usedRanage = xlWorkSheet.UsedRange;
foreach (Excel.Range row in usedRanage)
{
//grab name once selected in box
if (employeeBox.SelectedItem.Equals(row.Value))
{
row.EntireRow.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
MessageBox.Show("Employee Deleted.");
}
}
xlexcel.DisplayAlerts = false;
xlWorkBook.SaveAs("C:\\SAMPLE.xlsx", Excel.XlFileFormat.xlWorkbookDefault, Type.Missing,
Type.Missing, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlWorkBook.Close();
xlexcel.Quit();
releaseObject(xlexcel);
releaseObject(xlWorkBook);
releaseObject(xlWorkSheet);
}
private void delete_Click(object sender, EventArgs e)
{
//create excel
Excel.Application xlexcel = new Excel.Application();
Excel.Workbook xlWorkBook = xlexcel.Workbooks.Open(#"C:\\SAMPLE.xlsx");
int[] Cols = { 1 };
Excel.Range curRange;
foreach (Excel.Worksheet sheet in xlWorkBook.Worksheets)
{
foreach (Excel.Range row in sheet.UsedRange.Rows)
{
foreach (int c in Cols)
{
curRange = (Excel.Range)row.Cells[1, 1];
if (curRange.Cells.Value != null)
{
if (employeeBox.SelectedItem.Equals(sheet.Cells[row.Row, c].Value.ToString()))
{
row.EntireRow.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
MessageBox.Show("Employee Deleted.");
}
}
}
}
}
xlexcel.DisplayAlerts = false;
xlWorkBook.SaveAs("C:\\SAMPLE.xlsx", Excel.XlFileFormat.xlWorkbookDefault, Type.Missing,
Type.Missing, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlWorkBook.Close();
xlexcel.Quit();
releaseObject(xlexcel);
releaseObject(xlWorkBook);
}

Open an excel worksheet [duplicate]

I know we can open a particular worksheet of MS Excel using C# by providing the sheet number (1,2,3..) or name (sheet1, sheet2, sheet3...)
I have a excel file which has 2 sheets, 1. Values, 2. Results
Is there a way to open a sheet giving the sheet name ,i.e, "Values" instead of 1 or [s|S]heet1 in C# ??
I looked thru the old posts but didnt find anything useful...
so again, what I am trying to do is, open a Excel worksheet by using its user defined name (Values) instead of the system defined name(1 or [s|S]heet1)
any inputs would be greatly appreciated!
Add reference to Microsoft.Office.Interop.Excel in your project and you can use next code as base
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
//Start Excel and get Application object.
oXL = new Excel.Application();
oXL.Visible = false;
oXL.DisplayAlerts = false; // prevents message from popping up
try
{
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Open(filename, 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));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
int nCounter = 1;
oSheet.Copy(oSheet, Type.Missing);
Excel._Worksheet oSheetGame = (Excel._Worksheet)oWB.Worksheets["MyTemplate"];
oSheetGame.Name = "MyNewWorksheetName";
// do something with worksheet
((Excel._Worksheet)oWB.Sheets["MyTemplate"]).Delete(); // delete template
((Excel._Worksheet)oWB.Worksheets["MyNewWorksheetName"]).Activate();
}
catch (Exception e)
{
//throw e;
throw;
}
finally
{
//Make sure Excel is visible and give the user control
//of Microsoft Excel's lifetime.
oXL.Visible = true;
oXL.UserControl = true;
}
oXL.Save(Type.Missing);
#volody, thanks! your post helped a lot.
I took the worksheet declaration part from yours and changed mine into following:
Excel.Application excelApplication;
Excel.Worksheet excelWorksheet;
Excel.Workbook excelWorkbook;
Excel.Range range;
excelApplication = new Excel.Application();
excelWorkbook = (Excel.Workbook)(excelApplication.Workbooks.Open(
<FILENAME>,
Type.Missing, true, Type.Missing, Type.Missing, Type.Missing,
true, Type.Missing, Type.Missing, false, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing));
excelWorksheet = (Excel.Worksheet)excelWorkbook.Worksheets[<WORKSHEETNAME>];
The code above helps in opening a Excel Worksheet with a User defined name. For example, to open a Worksheet named Test instead of Sheet1.
Ivar

excel file to save value in cell range

protected void Page_Load(object sender, EventArgs e)
{
try
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Open(#"D:\Tesco\NGC\Output\temp_02Feb2012.xls", 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);
Worksheet sheet = (Worksheet)wb.Sheets["ExpiredAccount"];
Range excelRange = sheet.UsedRange;
Range rng1 = sheet.get_Range("A2", "A2");
rng1.Value2 = "India";
Range rng2 = sheet.get_Range("A3", "A3");
rng2.Value2 = "Good work";
// string A4D4 = GetRange("A" + 2 + ":A" + 2 + "", sheet);
}
catch (Exception ex)
{
throw ex;
}
}
i am trying to open an excel file and an particular sheet called[ExpiredAccount].where i need to set an value in that particular range
here is my code but its not saving the value only, its not throwing any error.
please let me know where i am going wrong it would great if you can help me on this
Thanks
Prince
you have to save the workbook. and release the runtime callable wrapper.
simply add this code:
wb.Close(true, Type.Missing, Type.Missing); //closes and saves the workbook
app.Quit();
Marshal.FinalReleaseComObject(app); //release the wrapper
p.s. if you weren't releasing the object, I suggest to run the Task manager, check the processes tab, and end all Excel.exe processes... there ought to be a lot of them :)

Open excel workbook but set calculations to manual

I have tried a few options but none seem to work, and some send errors.
Please let me know what I am doing wrong
public string Main(String wbPath, String wbName)
{
string cName = "";
Excel.Application xlApp;
Excel.Workbook xlWB;
Excel.Worksheet xlWS;
xlApp = new Excel.Application();
xlApp.DisplayAlerts = false;
xlApp.Calculation = Excel.XlCalculation.xlCalculationManual; //Error occurs here
xlWB = xlApp.Workbooks.Open(wbPath + wbName);
xlWB.SaveAs("vFile.html", Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml);
cName = xlWB.FullName;
xlWB.Close();
xlApp.Quit();
return cName;
}
Error code:
{"Exception from HRESULT: 0x800A03EC"}
You must open the workbook before setting the xlApp.Calculation:
static void Main(string[] args)
{
string cName = "";
var xlApp = new Application();
var xlWB = xlApp.Workbooks.Open("youpathgoeshere", 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);
xlApp.Calculation = XlCalculation.xlCalculationManual;
var xlWS = new Worksheet();
xlWB.SaveAs("vFile.html", Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml);
cName = xlWB.FullName;
xlWB.Close();
xlApp.Quit();
}
You can try this solution:
This example causes Microsoft Excel to calculate workbooks before they are saved to disk.
Excel.Application xlApp;
xlApp = new Excel.Application();
Application.Calculation = xlCalculationManual
Application.CalculateBeforeSave = True

Opening MS Excel worksheet in C#

I know we can open a particular worksheet of MS Excel using C# by providing the sheet number (1,2,3..) or name (sheet1, sheet2, sheet3...)
I have a excel file which has 2 sheets, 1. Values, 2. Results
Is there a way to open a sheet giving the sheet name ,i.e, "Values" instead of 1 or [s|S]heet1 in C# ??
I looked thru the old posts but didnt find anything useful...
so again, what I am trying to do is, open a Excel worksheet by using its user defined name (Values) instead of the system defined name(1 or [s|S]heet1)
any inputs would be greatly appreciated!
Add reference to Microsoft.Office.Interop.Excel in your project and you can use next code as base
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
//Start Excel and get Application object.
oXL = new Excel.Application();
oXL.Visible = false;
oXL.DisplayAlerts = false; // prevents message from popping up
try
{
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Open(filename, 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));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
int nCounter = 1;
oSheet.Copy(oSheet, Type.Missing);
Excel._Worksheet oSheetGame = (Excel._Worksheet)oWB.Worksheets["MyTemplate"];
oSheetGame.Name = "MyNewWorksheetName";
// do something with worksheet
((Excel._Worksheet)oWB.Sheets["MyTemplate"]).Delete(); // delete template
((Excel._Worksheet)oWB.Worksheets["MyNewWorksheetName"]).Activate();
}
catch (Exception e)
{
//throw e;
throw;
}
finally
{
//Make sure Excel is visible and give the user control
//of Microsoft Excel's lifetime.
oXL.Visible = true;
oXL.UserControl = true;
}
oXL.Save(Type.Missing);
#volody, thanks! your post helped a lot.
I took the worksheet declaration part from yours and changed mine into following:
Excel.Application excelApplication;
Excel.Worksheet excelWorksheet;
Excel.Workbook excelWorkbook;
Excel.Range range;
excelApplication = new Excel.Application();
excelWorkbook = (Excel.Workbook)(excelApplication.Workbooks.Open(
<FILENAME>,
Type.Missing, true, Type.Missing, Type.Missing, Type.Missing,
true, Type.Missing, Type.Missing, false, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing));
excelWorksheet = (Excel.Worksheet)excelWorkbook.Worksheets[<WORKSHEETNAME>];
The code above helps in opening a Excel Worksheet with a User defined name. For example, to open a Worksheet named Test instead of Sheet1.
Ivar

Categories