How to make font size bold in excel - c#

Nowadays am working on a c# desktop application and in this application after a transaction completed that transaction export in excel but I want to make an excel font size bold I don't know how to do it please help me in this scenario.
Thanks.
here is my code
//creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
//creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
//creating new Excelsheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
//see the excel sheet behind the program
app.Visible = true;
//get the reference of first sheet. By default its name is Sheet1.
//store its reference to worksheet
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
//changing the name of active sheet
worksheet.Name = "Exported from gridview";
//storing header part in Excel
//
worksheet.Cells[1, 1] = "Customer Name";
worksheet.Cells[1, 2] = "S/D/W";
worksheet.Cells[1, 3] = "NIC";
worksheet.Cells[1, 4] = "Postal Address";
worksheet.Cells[1, 5] = "Flat No";
worksheet.Cells[1, 6] = "Type";
worksheet.Cells[3, 1] = "Floor";
worksheet.Cells[3, 2] = "Block";
worksheet.Cells[3, 3] = "Size";
worksheet.Cells[3, 5] = "File No";
worksheet.Cells[3, 6] = "Nominee";
worksheet.Cells[5, 1] = "Relation";
worksheet.Cells[5, 2] = "nominee_NIC";
worksheet.Cells[5, 3] = "Contact_NIC";
worksheet.Cells[5, 4] = "Status";
worksheet.Cells[5, 5] = "Booking Station";
worksheet.Cells[5, 6] = "Booked By";
worksheet.Cells[7, 1] = "Cost";
worksheet.Cells[7, 2] = "Discount";
worksheet.Cells[7, 3] = "Total";
workbook.SaveAs("D:\\output.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

worksheet.Cells[1, 1].Font.Bold = true; should do the job

Related

C# saving excel file not getting saved

I am using this code to create an excel instance which is used for making a report
excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = true;
excel.DisplayAlerts = false;
worKbooK = excel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
worKsheeT = worKbooK.Worksheets[1]; ;
worKsheeT.Name = "Report";
iCountW = 2;
worKsheeT.Cells[1, 1] = "S.No";
worKsheeT.Cells[1, 2] = "Weld Stud/Nut Name";
worKsheeT.Cells[1, 3] = "Weld Spot Clearance Status";
worKsheeT.Cells[1, 4] = "Weld Spot Name";
worKsheeT.Cells[1, 5] = "Coord-X";
worKsheeT.Cells[1, 6] = "Coord-Y";
worKsheeT.Cells[1, 7] = "Coord-Z";
// Some Code
// Some more code
// No more code
After updating the data rows of this report I am using the below code for saving the excel workbook which is not letting me save the workbook.
string filename = Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory) + "\\" + "Trial_StudNut.xlsx";
if (!System.IO.File.Exists(filename))
{
worKbooK.SaveAs(filename, Excel.XlSaveAsAccessMode.xlNoChange);
}
Can someone help me with what am I missing to avoid exceptions while saving the workbook?
Edit: I am getting the following
(HRESULT: 0x800A03EC Error while saving Excel file)
The code is getting inside the condition and then falling into the exception.

interop error HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH) on server

I am having a problem with my app when trying to run on the server.
In my place it works fine but when passed to the server it fails to try to create the pivotcache.
Excel has permissions on the server with the user IIS, on my computer I have Office 365 and Office 2010 on server.
please help.error
Excel.Application oApp;
Excel.Worksheet oSheet;
Excel.Workbook oBook;
//Create COM Objects. Create a COM object for everything that is referenced
oApp = new Excel.Application();
oBook = oApp.Workbooks.Open(fileTest);
oSheet = oBook.Sheets[1];
//Range = oSheet.Range["A9","BN36"];
//Excel.Worksheet oSheet2 = oBook.Worksheets.Add();
//oSheet2.Name = "Pivot Table";
//oApp = new Excel.Application();
//oBook = oApp.Workbooks.Add();
//oSheet = (Excel.Worksheet)oBook.Worksheets.get_Item(1);
//oSheet.Cells[1, 1] = "Name";
//oSheet.Cells[1, 2] = "Salary";
//oSheet.Cells[2, 1] = "Frank";
//oSheet.Cells[2, 2] = 150000;
//oSheet.Cells[3, 1] = "Ann";
//oSheet.Cells[3, 2] = 300000;
Excel.Range last = oSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range range = oSheet.get_Range("A1", last);
int lastUsedRow = last.Row;
int lastUsedColumn = last.Column;
//// now capture range of the first sheet = I will need this to create pivot table
Excel.Range oRange = oSheet.Range["A1", "AJ708"];
// create second sheet
if (oApp.Application.Sheets.Count < 2)
{
oSheet = (Excel.Worksheet)oBook.Worksheets.Add();
}
else
{
oSheet = oApp.Worksheets[2];
}
oSheet.Name = "Resumen";
// specify first cell for pivot table
Excel.Range oRange2 = oSheet.Cells[1, 1];
// create Pivot Cache and Pivot Table heres trow exception error
Excel.PivotCache oPivotCache = (Excel.PivotCache)oBook.PivotCaches().Add(Excel.XlPivotTableSourceType.xlDatabase, oRange);
Excel.PivotTable oPivotTable = (Excel.PivotTable)oSheet.PivotTables().Add(PivotCache: oPivotCache, TableDestination: oRange2, TableName: "Summary");
solved.
trying change this line
var oPivotCache = pivotCaches.Create(Excel.XlPivotTableSourceType.xlDatabase, "Sheet1!$A$1:$AL$" + lastUsedRow);
the correct format to pass a range on office 2010 i think so.

Exporting SQL table to Excel in C# is randomly picking cells formats for dates

I am trying to export an SQL Dataset to an excel document.
At certain points when outputting the date fields the excel cells are being formatted at certain points as date cells and some as general.
This is causing the dates to display sometime in the format that I want, UK style day/month/year, in the American style month/day/year.
If it was just one way that would be fine because the report would be at least consistent. However the fact that the code will sometime output the correct format and sometimes won't is very annoying
My code so far:
private void doReport(DataSet myDS)
{
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
int i;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "Report produced on the " + System.DateTime.Now.ToString("dd/MM/yyyy");
xlWorkSheet.Cells[3, 1] = "Project Type";
xlWorkSheet.Cells[3, 2] = "Client";
xlWorkSheet.Cells[3, 3] = "Date Started";
xlWorkSheet.Cells[3, 4] = "Target Date";
xlWorkSheet.Cells[3, 5] = "Date Completed";
xlWorkSheet.Cells[3, 6] = "Stage Target";
xlWorkSheet.Cells[3, 7] = "Stage";
xlWorkSheet.Cells[3, 8] = "Assigned To";
xlWorkSheet.Cells[3, 9] = "Notes";
i = 4;
foreach (DataRow row in myDS.Tables[0].Rows)
{
xlWorkSheet.Cells[i, 1] = row["strProjectDescription"];
xlWorkSheet.Cells[i, 2] = row["strClient"];
DateTime dteProjStart = (DateTime)row["dteProjectStart"];
xlWorkSheet.Cells[i, 3] = dteProjStart.ToString("dd/MM/yyyy");
DateTime dteProjTarget = (DateTime)row["dteProjectTarget"];
xlWorkSheet.Cells[i, 4] = dteProjTarget.ToString("dd/MM/yyyy");
if (rbViewProjectsCompletedVal.Checked)
{
DateTime dteProjFin = (DateTime)row["dteProjectFinished"];
xlWorkSheet.Cells[i, 5] = dteProjFin.ToString("dd/MM/yyyy");
}
if (row.IsNull("dteProjectStageTarget") == false)
{
DateTime dteProjStageTar = (DateTime)row["dteProjectStageTarget"];
xlWorkSheet.Cells[i, 6] = dteProjStageTar.ToString("dd/MM/yyyy");
}
xlWorkSheet.Cells[i, 7] = row["strProjectStageDescription"];
xlWorkSheet.Cells[i, 8] = row["initials"];
xlWorkSheet.Cells[i, 9] = csSQL.runSQL("select strProjectNotes from tbl_AdminSupport_Projects where intASProjectID = " + row["intASProjectID"], "Management").Tables[0].Rows[0]["strProjectNotes"];
i++;
}
xlWorkSheet.Columns.AutoFit();
xlWorkSheet.Rows.AutoFit();
xlApp.Visible = true;
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
Dataset structure:
Any item prefixed with str is a nvarchar(max), dte is a date

Data copied from Textboxes to be displayed on Excel cell not display

I'm trying to copy data from textboxes and set them on specific cells on Excel file In which have 2 sheets and sheet 1 named as "PM" and sheet 2 named as "4-10-2018" the process successfully done but on the second sheet not display data properly.
I checked my code many times but found nothing to fix this issue.
Code:
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Worksheet xlsht = new Microsoft.Office.Interop.Excel.Worksheet();
string path = #"D:\test.xlsx";
xlsht = xlApp.Application.Workbooks.Open(path).Worksheets["PM"];
xlsht.Cells[11, 2] = UserNameTxt.Text + "#rasatop.com";
xlsht.Cells[11, 4] = UserNameTxt.Text;
xlsht.Cells[14, 2] = SerialTxt.Text;
xlsht.Cells[16, 2] = WLANMacTxt.Text;
xlsht.Cells[16, 3] = LANMacTxt.Text;
xlsht.Cells[16, 4] = IPTxt.Text;
xlsht.Cells[14, 5] = ComputerTxt.Text;
xlsht.Cells[16, 5] = BarcodeTxt.Text;
xlsht.Cells[18, 5] = CPUTxt.Text.Substring(0, 26);
xlsht.Cells[18, 4] = VGATxt.Text;
xlsht.Cells[18, 3] = RAMTxt.Text;
xlsht.Cells[27, 4] = OSTxt.Text;
xlsht.Cells[5, 4] = System.DateTime.Today;
xlsht.Cells[26, 4] = System.DateTime.Today;
xlsht.Cells[9, 5] = System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName;
xlApp.Visible = true;
Microsoft.Office.Interop.Excel.Worksheet xlsht2 = new Microsoft.Office.Interop.Excel.Worksheet();
xlsht2 = xlApp.Application.Workbooks.Open(path).Worksheets["4-10-2018"];
xlsht2.Cells[4, 2] = System.DateTime.Today;
xlsht2.Cells[6, 2] = UserNameTxt.ToString();
xlsht2.Cells[6, 4] = ComputerTxt.ToString();
xlsht2.Cells[6, 5] = BarcodeTxt;
And after executing the code run successfully but data displayed as below in Screenshot:
Display Error:
In some places you are putting calling the .ToString() method of the TextBox control into your spreadsheet cell rather than reading its UserNameTxt.Text property which will contain the value.
Here is your problem UserNameTxt.ToString(). You have to getText property for TextBox value. Convert UserNameTxt.ToString()to UserNameTxt.Text

How do I format my export to excel workbook in microsoft.office.interop.excel?

I have this export function that allows me to export 2 grid views into 2 separated worksheets in one excel.
But my problems are:
How can I have a usual popup window like usual download when I click on export button to prompt user to OPEN, SAVE AS, CANCEL of the download instead of saving it to a specific location (currently what I am doing in my codes)?
How can I set a code to enable wraptext = true for all my cells and also auto format the column height and width to fixed all the text so that it does not show ###### for date as an example when column width is too small when excel is opened.
protected void EXPORT_BUTTON_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
String DT1 = "Data table 1";
String DT2 = "Data table 2";
ExportToExcel(app, workbook, Gridview1, DT1, 1);
ExportToExcel(app, workbook, Gridview2, DT2, 2);
}
public void ExportToExcel(Microsoft.Office.Interop.Excel._Application app, Microsoft.Office.Interop.Excel._Workbook workbook, GridView gridview, string SheetName, int sheetid)
{
// see the excel sheet behind the program
app.Visible = true;
// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
worksheet = (Excel.Worksheet)workbook,Worksheets.Add();
// changing the name of active sheet
worksheet.Name = SheetName;
// storing header part in Excel
for (int i = 1; i < gridview.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = gridview.Columns[i - 1].HeaderText;
}
// storing Each row and column value to excel sheet
for (int i = 0; i < gridview.Rows.Count - 1; i++)
{
for (int j = 0; j < gridview.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = gridview.Rows[i].Cells[j].Text.ToString();
}
}
//save the application
workbook.SaveAs(#"C:\Users\test\Desktop\Test\" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
}
Modify the path of the excel file to save to a virtual path as follows
workbook.SaveAs(#"C:\Users\test\Desktop\Test\" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
change this to
workbook.SaveAs(#"~/ExcelFiles/Filename.xlsx" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Try the following code for displaying save as dialog
String FileName = "FileName.xlsx";
String FilePath = "~/ExcelFiles/FileName.xlsx";
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();
Try this:
Excel.Worksheet worksheet =(Excel.Worksheet)workbook.Worksheets["Sheet" + sheetid];
as specified by Laxmikant modify the code of your method "ExportToExcel" as follows.
public void ExportToExcel(Microsoft.Office.Interop.Excel._Application app, Microsoft.Office.Interop.Excel._Workbook workbook, GridView gridview, string SheetName, int sheetid)
{
// see the excel sheet behind the program
app.Visible = true;
worksheet = (Excel.Worksheet)workbook.Worksheets.Add();
// changing the name of active sheet
worksheet.Name = SheetName;
// storing header part in Excel
for (int i = 1; i < gridview.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = gridview.Columns[i - 1].HeaderText;
}
// storing Each row and column value to excel sheet
for (int i = 0; i < gridview.Rows.Count - 1; i++)
{
for (int j = 0; j < gridview.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = gridview.Rows[i].Cells[j].Text.ToString();
}
}
I removed these two lines of code and now there is no need of the parameter "Sheetid"
Excel.Worksheet worksheet =(Excel.Worksheet)workbook.Worksheets["Sheet" + sheetid];
worksheet = workbook.ActiveSheet;
Hope this will solve your issue
you haven't added worksheet in Workbook
try below code
worksheet = (Excel._Worksheet)oXL.Worksheets.Add();
worksheet.Name = SheetName;
set your headers using rangs
string[] colNames = new string[gv.Columns.Count];
int col = 0;
foreach(gvvolumns dc in GridView.Columns)
colNames[col++] = dc.ColumnName;
char lastColumn = (char)(65 + dtProducts.Columns.Count - 1);
oSheet.get_Range("A1", lastColumn + "1").Value2 = colNames;
oSheet.get_Range("A1", lastColumn + "1").Font.Bold = true;
oSheet.get_Range("A1", lastColumn + "1").VerticalAlignment
= Excel.XlVAlign.xlVAlignCenter;

Categories