我正在尝试转换包含学生 ID 的 csv 文件。在csv文件中,某些学生ID以0开头(例如00121334)问题是,当我打开转换后的excel文件时,Excel会删除所有前导零。 我的问题是如何保证Excel不会删除所有前导零? 我尝试过使用这个
destintationXLS.NumberFormat = "@";
,但我不太确定该把它放在哪里。
这是我的代码:
public bool FormatInputToXLS(string CSVInputF1le, string XLSOutputFile, out string errormsg)
{
bool isSuccess = faises
errorMsg = string.Emptys
Excel.Application xLApp2 = new Excel.Application();
try
{
if(x1App2 == nu11)
{
x1App2 = new Excel.Application
{
Visible = true,
DisplayAlerts = false,
SheetsInNeuhlorkbook= 1
};
}
bool fileExists =File.Exists(CSVInputFile);
bool fileExists2 = File.Exists(XLSOutputFile);
try
{
Excel.Workbook x1Book;
Excel.Workbook x1Book2;
xlBook = xLApp2.workbooks.Open(CSVInputFile);
if(fileExists2)
xlBook2 = xlApp2.Workbooks.Open(xLSOutputFile);
else
xlBook2 = xLApp2.Workbooks.Add(missing);
try
{
Excel.Worksheet x1Sheet = (Excel.Worksheet)xlBook.Worksheets.get_Item(1);
Excel.Worksheet xlSheet2 = (Excel.Worksheet)x1Bool2.Worksheets.get_Item(1);
xlSheet2.Cells[1, 1] = "Student ID";
int lastRow = 1;
if(FileExists)
{
int[] colsToCheck = { 1 };
List<int> nonEmpty = new List<int>();
for(int col = 0; col < colsToCheck.Length; col++)
{
nonEmpty.Add(((Excel.Range)x1Sheet.Cells[1, colsToCheck[col]]).End[Excel.X10irection.xlDown].Row);
}
lastRow = nonEmpty.Min();
}
Excel.Range sourceCSV = x1Sheet.get_Range(string.Concat("A1:A",lastRow));
Excel.Range destintationXLS = x1Sheet2.Range["A2"];
destintationXLS.NumberFormat = "@";
sourceCSV.Copy();
destintationXLS.PasteSpecial(Excel.XlPasteSpecialType.xlPasteValues);
for(int xlCol = 1; xlCol < xlSheet2.UsedRange.Columns.Count; xlCol++)
{
((Excel.Range)xlSheet2.Cells[1,xlCol]).EntireColumn.AutoFit();
}
if (fileExists2)
xlBook2.Save();
else
xlBook2.SaveAs(XLSOutputFile, Excel.XlFileFormat.xlOpenXMLWorkbook, missing,missing,missing,missing,Excel.XlSaveAsAccessMode.xlExclusive,missing,missing,missing,missing,missing);
isSuccess = true;
xlBook.CLose(0);
xlBook2.Close(0);
}
catch(Exception e)
{
errorMsg = string.Concat("Failed to update file. ", e.Message);
}
finally
{
xlBook.Close(0);
xlBook2.Close(0);
}
}
catch(Exception e1)
{
if (fileExists)
errorMsg = string.Concat("Failed to open file. ", e1.Message);
else
errorMsg = string.Concat("Failed to create file. ", e1.Message);
}
finally
{
CloseExcel(xlApp2)
}
}
catch(Exception e2)
{
errorMsg = string.Concat("Failed to open Excel application. ", e2.Message);
}
return isSuccess;
}
ps。代码上有一些错字,代码对我来说是有效的。问题是前导零