Excel格式行
我将创build一个Excel文件,其中包含一个姓名,一个date和一个“我的”私人跑比赛的代码。
它工作正常,但看起来不是很好。 如何格式化单元格以读取插入date和文本? 名称和内容根本无法读取
Excel.Application _xlApp = new Excel.Application(); Excel.Workbook _xlWorkBook; Excel.Worksheet _xlWorkSheet; object misValue = System.Reflection.Missing.Value; internal void CreateExcelFile(string writePath) { this.CreateHeader(); this.AddContent(); this.SaveFile(writePath); } private void CreateHeader() { _xlWorkBook = _xlApp.Workbooks.Add(misValue); _xlWorkSheet = (Excel.Worksheet)_xlWorkBook.Worksheets.get_Item(1); _xlWorkSheet.Cells[1, ExcelObject.SAMNAME] = "SAM_NAME"; _xlWorkSheet.Cells[1, ExcelObject.DATE] = "Date"; _xlWorkSheet.Cells[1, ExcelObject.CODE] = "Code"; FormatCells(_xlWorkSheet.Cells.Borders); } private void AddContent() { int i = 1; ++i; _xlWorkSheet.Cells[i, ExcelObject.Date] = DateTime.Now.ToString("yyyyMMdd_HHmmss"); _xlWorkSheet.Cells[i, ExcelObject.SAMNAME] = "Julek"; } private void FormatCells(Excel.Borders _borders) { _borders[Excel.XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlContinuous; _borders[Excel.XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlContinuous; _borders[Excel.XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlContinuous; _borders[Excel.XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlContinuous; _borders.Color = ConsoleColor.Black; } private void SaveFile(string writePath) { string fileName = string.Format("{0}_{1}.xls","SampleFile", DateTime.Now.ToString("yyyyMMdd_HHmmss")); _xlWorkBook.SaveAs(Path.Combine(writePath, fileName), Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); _xlWorkBook.Close(true, misValue, misValue); _xlApp.Quit(); ReleaseObject(_xlWorkSheet); ReleaseObject(_xlWorkBook); ReleaseObject(_xlApp); } private void ReleaseObject(object obj) { try { System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); obj = null; } catch (Exception) { throw; } finally { GC.Collect(); } }
指定整列的格式,并使用ToOADate()
方法而不是.ToString("yyyyMMdd_HHmmss")
:
// get the date cell Range rg = _xlWorkSheet.Cells[ExcelObject.DATE, ExcelObject.DATE]; // specify the format for the whole column rg.EntireColumn.NumberFormat = @"yyyyMMdd\_HHmmss"; // ... // write the current date _xlWorkSheet.Cells[i, ExcelObject.DATE] = DateTime.Now.ToOADate();
我已经将yyyyMMdd_HHmmss
的格式更改为yyyyMMdd\_HHmmss
,因为Excel会将_
转换为空格,并保持下划线原样。
列的宽度可以以这种方式自动改变(在编辑结束时调用这个方法):
rg.EntireColumn.AutoFit();
插入所有数据时,最后应该调用AutoFit
方法。 当它被调用时它只改变一次宽度,但不是连续的。