我必须将datagridview提取到Excel文件中。进入Excel,我有很多数据,例如当前日期。
我按照range.Cells.NumberFormat = "General";
的说明选择了单元格格式,但是如果我的当前日期的天数小于或等于12,则将月份和日期颠倒。
我的日期格式是dd / mm / yyyy,如果我有当前日期,例如25/08/2018,没有问题,但是如果我有一个日期,例如04/09/2018,则进入单元格,我有09 / 04/2018。
这是我完成的代码
private void CreateExcel(string _FileName, ArrayList header, ArrayList recordColl, int codLoanPosition)
{
ApplicationClass xlsApplication = null;
Worksheet xlsWks = null;
CultureInfo originalCultureInfo = null;
Workbook currentWorkbook = null;
Range range = null;
string currentRow = "";
string codLoan = "";
bool primaRiga = true;
try
{
log.Info("creazione oggetto CultureInfo ");
originalCultureInfo = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
log.Info("creazione oggetto excel ");
xlsApplication = new ApplicationClass();
xlsApplication.Visible = false;
log.Info("apertura file csv ");
currentWorkbook = xlsApplication.Workbooks.Open(_FileName + ".csv", 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);
xlsWks = (Worksheet)currentWorkbook.ActiveSheet;
System.Drawing.Color interiorColor = System.Drawing.Color.FromArgb(153, 204, 255);
//System.Drawing.Color interiorColorRow = System.Drawing.Color.FromArgb(195, 195, 195);
log.Info("Create Excel range");
range = xlsWks.get_Range(xlsWks.Cells[1, 1], xlsWks.Cells[1, header.Count]);
range.Cells.NumberFormat = "General";
range.Interior.Color = System.Drawing.ColorTranslator.ToOle(interiorColor);
range.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
range.Font.Size = 12;
range.Font.Bold = true;
range.RowHeight = 30;
xlsWks.Cells.Columns.AutoFit();
log.Info("salvataggio excel ");
//Salva il file
currentWorkbook.SaveAs(_FileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
log.Info("completamento salvataggio excel ");
}
catch (Exception e)
{
//
log.Info("Eccezione in conversione in xls: " + e.Message);
}
finally
{
currentWorkbook.Close(false, Type.Missing, Type.Missing);
if (xlsApplication.Workbooks.Count == 0)
xlsApplication.Quit();
Thread.CurrentThread.CurrentCulture = originalCultureInfo;
GC.Collect();
}
我已经调试了我的代码,它执行了更改格式的指令。当我提取Excel文件时,所有单元格都是通用格式,但日期具有上面我告诉过你的特征。
我怎么做错了?
编辑:我没有以正确的方式解决我的问题,但是它可以正常工作。我为包含日期值的单元格创建了另一个范围,并使用此指令rangeDate.EntireColumn.NumberFormat = "mm/dd/yyyy";
我不知道它为什么起作用,但是通过这种方式,我的日期和月份处于正确的位置。如果找到最佳解决方案,我将再次编辑这篇文章