Date format change in Excel using C# - c#

I have an issue while exporting content to excel. If it's an MM/dd/yyyy date then excel is taking it as a date format. If we format into dd/MM/yyyy then it's considered to be a custom format in excel.
Below is my code:
private string GetFormattedDateforCreation(string datestring) //yyyyMMdd
{
if (string.IsNullOrEmpty(datestring))
{
return null;
}
else
{
return DateTime.ParseExact(datestring, "yyyyMMdd", CultureInfo.GetCultureInfo("fr-CA")).ToString("dd/MM/yyyy");
}
}
Excel Generate
Clipboard.Clear();
// Bulk insertion of Data into Trigger Element Excel
bool multiselect1 = dgvElement.MultiSelect;
dgvElement.MultiSelect = true;
dgvElement.SelectAll();
dgvElement.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText;
Clipboard.SetDataObject(dgvElement.GetClipboardContent());
var resultElement = System.Convert.ToString(Clipboard.GetData(DataFormats.Text));
dgvElement.ClearSelection();
dgvElement.MultiSelect = multiselect1;
Microsoft.Office.Interop.Excel.Application XCELAPPELEMENT = null;
Microsoft.Office.Interop.Excel.Workbook XWORKBOOKELEMENT = null;
Microsoft.Office.Interop.Excel.Worksheet XSHEETELEMENT = null;
object misValueElement = System.Reflection.Missing.Value;
XCELAPPELEMENT = new Microsoft.Office.Interop.Excel.Application();
XWORKBOOKELEMENT = XCELAPPELEMENT.Workbooks.Open(ExcelFilePath);
XCELAPPELEMENT.DisplayAlerts = false;
XCELAPPELEMENT.Visible = false;
XSHEETELEMENT = XWORKBOOKELEMENT.ActiveSheet;
XSHEETELEMENT.Paste();
XWORKBOOKELEMENT.SaveAs(Path.Combine(basePath, _frmSwip.OutputExcelFilePath, "SWIP_ElementsDeclencheurs_" + DateTime.Now.ToString("dd_mm_yyy HH_ss_mm")), Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook);
XWORKBOOKELEMENT.Close(true);
XCELAPPELEMENT.Quit();
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(XSHEETELEMENT);
System.Runtime.InteropServices.Marshal.ReleaseComObject(XWORKBOOKELEMENT);
System.Runtime.InteropServices.Marshal.ReleaseComObject(XCELAPPELEMENT);
}
catch
{
return "0";
}

Related

Issue with DateFormat in Excel while using OpenXMLWriter

I am trying to write excelsheet with data formatting. I have used the logic mentioned here https://www.codeproject.com/Articles/877791/How-to-Create-Large-Excel-File-using-Openxml
The problem I am facing is I need the date to be in UK format DD-MM-YYYY. SO I have changed
NumberingFormat nf;
nf = new NumberingFormat();
nf.NumberFormatId = iExcelIndex++;
// nf.FormatCode = #"[$-409]m/d/yy\ h:mm\ AM/PM;#";Changed this to below
nf.FormatCode = #"[$-409]dd/mm/yyyy;#";
But now the date comes out as XX-01-1900 the Month and Year are defaulting to 01 and 1900.
Would be great if someone can point me in a right direction.
The following works for me:
I am adding a date on cellRef A1
static void Main(string[] args)
{
string excelFilePath = "Test1.xlsx";
string text = "02-25-1999";
string sheetName = "Sheet1";
using (SpreadsheetDocument spreadsheetDoc = SpreadsheetDocument.Open(excelFilePath, true))
{
var stylesheet = spreadsheetDoc.WorkbookPart.WorkbookStylesPart.Stylesheet;
var numberingFormats = stylesheet.NumberingFormats;
const string dateFormatCode = "dd/mm/yyyy";
var dateFormat =
numberingFormats.OfType<NumberingFormat>()
.FirstOrDefault(format => format.FormatCode == dateFormatCode);
if (dateFormat == null)
{
dateFormat = new NumberingFormat
{
NumberFormatId = UInt32Value.FromUInt32(164),
// Built-in number formats are numbered 0 - 163. Custom formats must start at 164.
FormatCode = StringValue.FromString(dateFormatCode)
};
numberingFormats.AppendChild(dateFormat);
numberingFormats.Count = Convert.ToUInt32(numberingFormats.Count());
stylesheet.Save();
}
// get the (1-based) index
var dateStyleIndex = numberingFormats.ToList().IndexOf(dateFormat) + 1;
var worksheetPart = GetWorksheetPartByName(spreadsheetDoc, "Sheet1");
Row row1 = worksheetPart.Worksheet.GetFirstChild<SheetData>().Elements<Row>().FirstOrDefault();
Cell cell = row1.Elements<Cell>().FirstOrDefault();
DateTime dateTime = DateTime.Parse(text);
double oaValue = dateTime.ToOADate();
cell.CellValue = new CellValue(oaValue.ToString(CultureInfo.InvariantCulture));
cell.StyleIndex = Convert.ToUInt32(dateStyleIndex);
worksheetPart.Worksheet.Save();
spreadsheetDoc.WorkbookPart.WorkbookStylesPart.Stylesheet.Save();
}
Console.ReadKey();
}
Where GetWorksheetPartByName is:
private static WorksheetPart GetWorksheetPartByName(SpreadsheetDocument document, string sheetName)
{
IEnumerable<Sheet> sheets =
document.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>().Where(s => s.Name == sheetName);
if (!sheets.Any())
{
// The specified worksheet does not exist.
return null;
}
string relationshipId = sheets.First().Id.Value;
WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(relationshipId);
return worksheetPart;
}
Dates in excel are just number of days from the default date. Compute the number to insert and then apply the desired styling over the cell.

Display and read an Excel file into a datagridview

I have successfully displayed the data using a code I found at this particular website. The problem is, the colour, bold or italics of the font isn't carried over. I need to read the code of a specific cell and convert it into a HTML string and display it as a textbox elsewhere. So I really need to learn how to import colour, bold or italics so I can convert it too. I will be eternally grateful to any kind soul who helps me on this one. Below is my current code.
string PathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
OleDbConnection conn = new OleDbConnection(PathConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from [sheet1$]", conn);
DataTable dt = new DataTable();
myDataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
The following opens an Excel file in the app folder, get cell value, fore color, see if bold and italic is set for range sheet1 cell H2. Please note there is a decent amount of code which is warranted so that all objects used here are released upon finishing our work.
using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsFormsApplication1_CS
{
public class ExcelCode
{
public System.Drawing.Color ForeColor;
public ExcelCode() { }
public string GetCellValue(
string FileName,
string SheetName,
string CellAddress)
{
string CellValue = "";
if (System.IO.File.Exists(FileName))
{
bool Proceed = false;
Excel.Application xlApp = null;
Excel.Workbooks xlWorkBooks = null;
Excel.Workbook xlWorkBook = null;
Excel.Worksheet xlWorkSheet = null;
Excel.Sheets xlWorkSheets = null;
Excel.Range xlCells = null;
xlApp = new Excel.Application();
xlApp.DisplayAlerts = false;
xlWorkBooks = xlApp.Workbooks;
xlWorkBook = xlWorkBooks.Open(FileName);
xlApp.Visible = false;
xlWorkSheets = xlWorkBook.Sheets;
for (int x = 1; x <= xlWorkSheets.Count; x++)
{
xlWorkSheet = (Excel.Worksheet)xlWorkSheets[x];
if (xlWorkSheet.Name == SheetName)
{
Proceed = true;
break;
}
System.Runtime.InteropServices
.Marshal.FinalReleaseComObject(xlWorkSheet);
xlWorkSheet = null;
}
if (Proceed)
{
xlCells = xlWorkSheet.Range[CellAddress];
try
{
Console.WriteLine("Bold: {0}", xlCells.Font.Bold); // bool
Console.WriteLine("Italic: {0}", xlCells.Font.Italic); // bool
ForeColor = System.Drawing.ColorTranslator.FromOle((int)xlCells.Font.Color);
CellValue = Convert.ToString(xlCells.Value);
}
catch (Exception)
{
// Reduntant
CellValue = "";
}
}
else
{
MessageBox.Show(SheetName + " not found.");
}
xlWorkBook.Close();
xlApp.UserControl = true;
xlApp.Quit();
ReleaseComObject(xlCells);
ReleaseComObject(xlWorkSheets);
ReleaseComObject(xlWorkSheet);
ReleaseComObject(xlWorkBook);
ReleaseComObject(xlWorkBooks);
ReleaseComObject(xlApp);
}
else
{
MessageBox.Show("'" + FileName +
"' not located. Try one of the write examples first.");
}
return CellValue;
}
public static void ReleaseComObject(object obj)
{
try
{
if (obj != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
}
catch (Exception)
{
obj = null;
}
}
}
}
Form code which works from a button and has a panel
var demoExcel = new ExcelCode();
// open an Excel file in the app folder, get information from H2 in Sheet1
textBox1.Text = demoExcel
.GetCellValue(
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Demo.xlsx"),
"Sheet1",
"H2");
// Form has a panel, set back color to Sheet1.H2 color
panel1.BackColor = demoExcel.ForeColor;
// Translate the color to HTML
var htmlColor = System.Drawing.ColorTranslator.ToHtml(demoExcel.ForeColor);
Console.WriteLine(htmlColor.ToString());

System.Runtime.InteropServices.COMException when I use Microsoft.interop.Excel.dll

I use Microsoft.interop.Excel.dll to convert Excel to .pdf. The core code:
using Microsoft.Office.Interop.Excel;
using ExcelApplicationClass = Microsoft.Office.Interop.Excel.ApplicationClass;
public static bool ExcelToPdf(string sourcePath, string targetPath, out string exmsg)
{
exmsg = string.Empty;
bool result = false;
object missing = Type.Missing;
ExcelApplicationClass applicationClass = null;
Workbook workBook = null;
try
{
applicationClass = new ExcelApplicationClass();
applicationClass.Visible = false;
/* applicationClas*/
workBook = applicationClass.Workbooks.Open(sourcePath);
if (workBook != null)
{
Microsoft.Office.Interop.Excel.Worksheet worksheet = workBook.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;
//*** if I annotation the block in this if. the code no error occured.
if (worksheet != null)
{
worksheet.PageSetup.Zoom = false;
worksheet.PageSetup.FitToPagesWide = 1;
}
workBook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, targetPath, XlFixedFormatQuality.xlQualityMinimum, false, true);
}
result = true;
}
catch (Exception ex)
{
exmsg = ex.Message;
result = false;
}
finally
{
if (workBook != null)
{
workBook.Close(true,missing, missing);
workBook = null;
}
if (applicationClass != null)
{
applicationClass.Quit();
applicationClass = null;
}
}
return result;
}
If I don't set worksheet.PageSetup's property like zoom etc. the program runs well but if I set the property System.Runtime.InteropServices.COMException will occur nine times out of ten. Sometime there is no error.
The error info
The environment information
Microsoft Excel 2013
Windows 10
Every time it has killed the Microsoft Excel progress.

C# not creating the excel file and cannot write in different excel sheets

First of all in my code im opening an excel sheet and reading it into a list. Second of all im closing this excel sheet and creating a new excel sheet:
excel_init("C:\\Users\\oma\\Desktop\\excel2.xlsx"); // this path does NOT exist yet
Next its going to this method:
static void excel_init(String path)
{
appExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
if (System.IO.File.Exists(path))
{
// then go and load this into excel
newWorkbook_First = appExcel.Workbooks.Open(path, true, true);
objsheet = (_Worksheet)appExcel.ActiveWorkbook.ActiveSheet;
}
else
{
try
{
appExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
appExcel.Visible = true;
newWorkbook_First = appExcel.Workbooks.Add(1);
objsheet = (Microsoft.Office.Interop.Excel.Worksheet)newWorkbook_First.Sheets[1];
objsheet.Name = ("test");
var newSheet3 = (Microsoft.Office.Interop.Excel.Worksheet)appExcel.Worksheets.Add(Type.Missing, appExcel.Worksheets[appExcel.Worksheets.Count], 1, XlSheetType.xlWorksheet);
newSheet3.Name = "test2";
var newSheet2 = (Microsoft.Office.Interop.Excel.Worksheet)appExcel.Worksheets.Add(Type.Missing, appExcel.Worksheets[appExcel.Worksheets.Count], 1, XlSheetType.xlWorksheet);
newSheet2.Name = "test3";
}
catch (Exception e)
{
Console.Write("Error");
}
finally
{
}
}
}
It wont create excel2.xlsx on my desktop, why not?
Next in my main I am shouting excel_setValue this way:
excel_setValue("C", "hello", "");
This is the excel_setValue function:
static void excel_setValue(string cellname, string value, string color)
{
objsheet.get_Range(cellname).set_Value(Type.Missing, value);
if (kleur == "red")
{
objsheet.get_Range(cellname).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
}
}
How do I add the sheet to this? For exmaple: excel_setValue(cellname, value, color, sheetname)
Finally I do excel_close();
the excel_close function:
static void excel_close()
{
if (appExcel != null)
{
try
{
newWorkbook_First.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel.ActiveWorkbook.ActiveSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel.ActiveWorkbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel);
appExcel = null;
objsheet = null;
}
catch (Exception ex)
{
appExcel = null;
Console.WriteLine("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
It closes and ask me if I wanna save/not-save or cancel it. And it will save # documents with no errors given
I create my Excel like this worked fine for me!
You need to do the folowing in you code before the newWorkbook_First.close(); part:
newWorkbook_First.SaveAs(totalPath);
I hope this will help you solve the problems..
using Excel = Microsoft.Office.Interop.Excel;
internal static bool ExportDGV(DataGridView DGV, List<string> selectedCustomerList, string path, string fileName, string exportName, int exportType, string mailSubject)
{
string totalPath;
//Create an Excel application instance
Excel.Application excelApp = new Excel.Application();
Excel.Workbook excelWorkBook = excelApp.Application.Workbooks.Add();
Excel._Worksheet worksheet = null;
excelApp.Visible = false;
worksheet = excelWorkBook.ActiveSheet;
//set headers
for (int i = 1; i < DataGridView.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = DGV.Columns[i - 1].HeaderText;
}
createList(worksheet, DGV);
//Create excel with the choosen name
Worksheet sheet1 = excelWorkBook.Worksheets[1];
worksheet.Name = fileName;
totalPath = path + "/" + fileName + ".xlsx";
//if path exist add a number
totalPath = directoryExist(totalPath, path, fileName);
//Save exel and Quit exelApp
excelWorkBook.SaveAs(totalPath);
excelWorkBook.Close();
excelApp.Quit();
}
You can use EpPlus library for excel. It is very easy to use and well documented. You don't need to use COM classes anymore

Split xml string in c#

I want to store xml file in excel. For that I converted xml to string and stored it in cell. Since excel cell can't support more than 32767 characters so I splitted the xml on the basis of character count and stored the splitted xml in different cells. but the problem is that at the time of reading xml, an error occurs because the xml is getting corrupted. Here is the code. Any help would be great. I would like to know if any new way can be suggested to do so.
private void SaveXml(XmlDocument xmlDoc)
{
Excel.Workbook WB = Globals.ThisAddIn.Application.ActiveWorkbook;
string strXml = string.Empty;
if (xmlDoc != null)
strXml = xmlDoc.OuterXml;
else
return;
Excel.Worksheet ws = null;
try
{
ws = WB.Sheets["XML"];
}
catch
{
ws = (Excel.Worksheet)WB.Sheets.Add(After: WB.Sheets[WB.Sheets.Count]);
ws.Name = "XML";
WB.Save();
}
int MergeCount = 1;
if (strXml.Length > 32700)
{
while (strXml.Length > 32700)
{
ws.Cells[MergeCount, 1] = strXml.Substring(0, 32699);
strXml = strXml.Substring(32700);
MergeCount++;
}
ws.Cells[MergeCount, 1] = strXml;
}
else
ws.Cells[1, 1] = strXml;
}
private XmlDocument GetXml()
{
Excel.Workbook WB = Globals.ThisAddIn.Application.ActiveWorkbook;
XmlDocument xmlDoc = new XmlDocument();
string strXml = string.Empty;
int XmlColumn = 1;
try
{
Excel.Worksheet ws = WB.Sheets["XML"];
while (ws.Cells[XmlColumn, 1].Value != null)
{
strXml = strXml + ws.Cells[XmlColumn, 1].Value.ToString();
XmlColumn++;
}
xmlDoc.LoadXml(strXml);
}
catch
{
MessageBox.Show("Xml not found.");
}
return xmlDoc;
}
Makes me wonder why you want to store an xml file in a cell... seems an odd thing to do... the issue you have about splitting them is it is no longer a valid xml scheme...
I know it's an old link but take a look here for a way to import xml data into a workbook (using xsl)

Categories