目前我在Excel中的日期存在一个奇怪的问题,从网格中导出时某些日期显示文件时交换了日期和日期,但是我使用数字格式来解决这个问题,但是某些项目似乎仍然存在问题
private static void ExportToExcel(List<ListViewItem> items, ListView listView)
{
using (var progressIndicatorForm = new ProgressIndicatorForm(0, items.Count))
{
try
{
progressIndicatorForm.Show();
System.Windows.Forms.Application.DoEvents();
Microsoft.Office.Interop.Excel.Application app = null;
Microsoft.Office.Interop.Excel.Workbook workBook = null;
Microsoft.Office.Interop.Excel.Worksheet workSheet = null;
try
{
app = new Microsoft.Office.Interop.Excel.Application();
workBook = app.Workbooks.Add(1);
workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Worksheets[1];
List<string> columnNames = GetColumnNames(listView);
for (int columnIndex = 0; columnIndex < columnNames.Count; columnIndex++)
{
workSheet.Cells[0 + 1, columnIndex + 1] = columnNames[columnIndex];
}
for (int rowIndex = 1; rowIndex <= items.Count; rowIndex++)
{
progressIndicatorForm.Current = rowIndex;
progressIndicatorForm.Description = string.Format("Exporting {0} of {1} records...", rowIndex, items.Count);
System.Windows.Forms.Application.DoEvents();
var item = items[rowIndex - 1];
for (var columnIndex = 0; columnIndex < listView.Columns.Count; columnIndex++)
{
var column = listView.Columns[columnIndex];
if (column.Tag != null && column.Tag.ToString() == typeof(DateTime).ToString())
{
string text = item.SubItems[columnIndex].Text;
DateTime? dateTime = ParseDateTime(text);
if (dateTime.HasValue)
{
Range range = (Range)workSheet.Cells[rowIndex + 1, columnIndex + 1];
range.Value = dateTime.Value.ToOADate();
range.NumberFormat = "dd/MM/yyyy";
}
else
{
workSheet.Cells[rowIndex + 1, columnIndex + 1] = text;
}
}
else
{
workSheet.Cells[rowIndex + 1, columnIndex + 1] = item.SubItems[columnIndex].Text;
}
}
}
app.Visible = true;
}
catch (Exception ex)
{
ExceptionManager.HandleUnexpectedException(ex);
}
finally
{
app = null;
workBook = null;
workSheet = null;
}
}
catch (Exception ex)
{
ExceptionManager.HandleUnexpectedException(ex);
}
finally
{
progressIndicatorForm.Close();
}
}
}
如您所见,我正在使用以下方法,这是dd / mm / yyyy的建议方法
range.NumberFormat =“ dd / MM / yyyy”;