I am creating an excel file using a data table in excel interop
Price Profit/Loss%
250.8982989 0.04301071
I have a schema file which has details for design as
1) make all headers bold
2) column definition (weather,string,percentage)
I used this file in fast report export but as such i have to use interop for excel export is there a way i can add that schema file
Excel.Application excelApp = new Excel.Application();
//Create an Excel workbook instance and open it from the predefined location
Excel.Workbook excelWorkBook = excelApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
//Add a new worksheet to workbook with the Datatable name
Excel.Worksheet excelWorkSheet = (Excel.Worksheet)excelWorkBook.Sheets.Add();
for (int i = 1; i < table.Columns.Count + 1; i++)
{
excelWorkSheet.Cells[1, i] = table.Columns[i - 1].ColumnName;
}
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();
}
}
excelWorkBook.SaveAs(#"D:\sample excel.xls");
excelWorkBook.Close();
excelApp.Quit();
i want to show this value in bold and format as % 0.04301071
make this value Bold and round 250.8982989
This all information will be stored in a schema file i want to load that file
or else i want to load that cell as per the columns datatype in datatable
I have tried :-
clmnrange.NumberFormat = (Object)table.Columns[k - 1].DataType;
but it is raising an exception
Regards
EP
As mentioned in above comment:
The NumberFormat property takes a string that uses Excel's formatting
syntax. For example formatting as a percentage (up to) 8 decimal
places is "0.########%"
Here is an example that someone else provided showing how to implement the type of numberingFormat you are describing:
WorkbookStylesPart sp = workbookPart.AddNewPart<WorkbookStylesPart>();
Create a stylesheet:
sp.Stylesheet = new Stylesheet();
Create a numberingFormat:
sp.Stylesheet.NumberingFormats = new NumberingFormats();
// #.##% is also Excel style index 1
NumberingFormat nf2decimal = new NumberingFormat();
nf2decimal.NumberFormatId = UInt32Value.FromUInt32(3453);
nf2decimal.FormatCode = StringValue.FromString("0.0%");
sp.Stylesheet.NumberingFormat.Append(nf2decimal);
Related
I need to read an excel file after reading it I need to do a mapping
to a DataGridView.
This is the code I've tried:
DataTable dt = new DataTable();
Microsoft.Office.Interop.Excel.Application exlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook exlWb = exlApp.Workbooks.Open(#"C:\Users\HP8200\Desktop\2003.xls");
Microsoft.Office.Interop.Excel.Worksheet exlWs = exlWb.Sheets["PARAC1"];
Microsoft.Office.Interop.Excel.Range usedRange = exlWs.UsedRange;
int col = Convert.ToInt32(usedRange.Columns.Count);
int row = Convert.ToInt32(usedRange.Rows.Count);
exlApp.Visible = true;
string[,] cellValue = new string[row + 1, col + 1];
for (int j = 1; j <= row - 1; j++)
{
for (int k = 1; k <= col - 1; k++)
{
cellValue[j, k] = exlWs.Cells[j, k + 1].ToString();
dt.Rows[j]["Customer No"] = cellValue[j, 1];
dt.Rows[j]["Card Prog"] = cellValue[j, 2];
dt.Rows[j]["LOS No"] = cellValue[j, 3];
}
}
exlWb.Close();
exlWs = null;
exlWb = null;
exlApp.Quit();
exlApp = null;
dataGridView1.DataSource = dt;
there are some good answers here:
How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries
It is always a good idea to read an excel file without being required to have office installed and you will see there an answer related to this, there are libraries that can do that for you easily.
Next, try to apply a little SOC ( separation of concerns ) in your code. This means you build a layer responsible for reading your excel files and that one returns some data in a format you can use in the UI. That's the layer you call and then you apply the results of that call to your DataGrid or whatever other UI thing you want to display it in.
I created Excel file using this code:
Sheets worksheets = wb.Sheets;
Worksheet worksheet = (Worksheet)worksheets[4];
int rows = dt.Rows.Count;
int columns = dt.Columns.Count;
var data = new object[rows + 1, columns];
for (var column = 0; column < columns; column++)
{
data[0, column] = dt.Columns[column].ColumnName;
}
for (var row = 0; row < rows; row++)
{
for (var column = 0; column < columns; column++)
{
data[row + 1, column] = dt.Rows[row][column];
}
}
Range beginWrite = (Range)worksheet.Cells[1, 1];
Range endWrite = (Range)worksheet.Cells[rows + 1, columns];
Range sheetData = worksheet.Range[beginWrite, endWrite];
sheetData.Value2 = data;
worksheet.Select();
sheetData.Worksheet.ListObjects.Add(XlListObjectSourceType.xlSrcRange,
sheetData,
Type.Missing,
XlYesNoGuess.xlNo,
Type.Missing);
sheetData.Select();
Excel.ActiveWindow.DisplayGridlines = false;
Excel.Application.Range["2:2"].Select();
Excel.Application.Range["$A$3"].Select();
the problem here it set default format style to excel fileI don't know how to clear all format style in excel sheet
If all you are trying to do is delete all styles, this would work:
using Excelx = Microsoft.Office.Interop.Excel;
Excelx.Workbook wb = excel.ActiveWorkbook;
foreach (Excelx.Style st in wb.Styles)
st.Delete();
Then again, you may only want to clear out custom styles (not the ones that come standard), in which case a small modification would do it:
foreach (Excelx.Style st in wb.Styles)
{
if (!st.BuiltIn)
st.Delete();
}
Styles are stored at the workbook level, so at some point you need to declare your workbook. From there, the Styles collection of the Workbook object has everything you need.
I have made a simple inventory interface that will take data from access and show in datagrid view on my interface and then send the information to Excel via button click. This part works as needed but I would like to remove the unused columns and rows after the information is sent. I am currently using VS 2015. I cant figure out what to add to accomplish this.
//send to excel
private void btnExport_Click(object sender, EventArgs e)
{
ActiveControl = txtSerial;
// 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 = "Inventory Search";
// storing header part in Excel
for (int i = 1; i < dataGridFB.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = dataGridFB.Columns[i - 1].HeaderText;
worksheet.Cells[1, i].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightBlue);
worksheet.Cells[1, i].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
worksheet.Cells[1, i].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
worksheet.Cells[1, i].Font.Size = 14;
}
// storing Each row and column value to excel sheet
for (int i = 0; i < dataGridFB.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridFB.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridFB.Rows[i].Cells[j].Value.ToString();
worksheet.Cells[i + 2, j + 1].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
worksheet.Cells[i + 2, j + 1].Font.Size = 12;
worksheet.Columns["A:G"].AutoFit();
}
}
}
Your question is a bit too broad, thus the answer is generic: in order to delete entire Worksheet Column you may use VBA statement like: Columns("C").Delete, or Columns(3).EntireColumn.Delete, or Columns("F:K").Delete. Similar syntax may apply to: Rows(3).Delete.
In order to just hide Rows/Columns use the VBA statement like shown below:
Rows("3:10").EntireRow.Hidden = True
Columns("C").Hidden = True
Hope this may help.
Please consider this code:
Microsoft.Office.Interop.Excel.Application objApp;
Microsoft.Office.Interop.Excel._Workbook objBook;
Microsoft.Office.Interop.Excel.Workbooks objBooks;
Microsoft.Office.Interop.Excel.Sheets objSheets;
Microsoft.Office.Interop.Excel._Worksheet objSheet;
Microsoft.Office.Interop.Excel.Range range;
int ColumnsCount = dt.Columns.Count;
int RowsCount = dt.Rows.Count;
objApp = new Microsoft.Office.Interop.Excel.Application();
objBooks = objApp.Workbooks;
objBook = objBooks.Add(System.Reflection.Missing.Value);
objSheets = objBook.Worksheets;
objSheet = (Microsoft.Office.Interop.Excel._Worksheet)objSheets.get_Item(1);
for (int i = 1; i < ColumnsCount + 1; i++)
{
objSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
}
range = objSheet.get_Range("A2", System.Reflection.Missing.Value);
range = range.get_Resize(RowsCount, ColumnsCount);
string[,] saRet = new string[RowsCount, ColumnsCount];
for (int iRow = 0; iRow < RowsCount; iRow++)
{
for (int iCol = 0; iCol < ColumnsCount; iCol++)
{
saRet[iRow, iCol] = dt.Rows[iRow][iCol].ToString();
}
}
//Set the range value to the array.
range.set_Value(Missing.Value, saRet);
I want to download Excel object that I created. The problem is Microsoft.Office.Interop.Excel._Workbook is not serializable and until I save it I can't access Excel file. How I can download Excel that created in memory?
thanks
This seems like one of the many problems related to Microsoft KB: Considerations for server-side Automation of Office. Using Excel Interop server-side isn't supported.
I'd recommend you export csv files or look into OpenXML or the easier version ClosedXML to generate xslx files on the server.
See the other methods in this MSDN guide: How To Asp.Net Export Excel
There should be a SaveAs method on your workbook that you can use to save as an xls file.
objBook.SaveAs("my-workbook.xls");
I have an Excel file and I need to copy data from one column. But I don't know how many rows are there.
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp = new Excel.Application();
Excel.Workbook _workBook = xlApp.Workbooks;
Excel.Worksheet _workSheet = (Excel.Worksheet) _workBook.Worksheets[1];
How can I copy data?
Range range = _workSheet .UsedRange;
int rows = range.Rows.Count;
int cols = range.Columns.Count;
// nested loops to take values from used range of cell one by one
for(int r=1; r <= rows; r++)
for(int c=1; c <= cols; c++)
object cellValue = range.Cells[r,c].Value2;
// take values from one row
int row = 1;
for(int c=1; c <= cols; c++)
object cellValue = range.Cells[row,c].Value2;
since you didn't provide any information about the library you are using for working with excel, i will assume you are using Interop Services:
int columns = _workSheet.Columns.Count;
int rows = _workSheet.Rows.Count;
int cells = columns*rows
string cellValue = (string)((Excel.Range)_workSheet.Cells[1, 1]).Value;