im试图导出包含多张工作表的excel文件,并且每张工作表都有一个数据(可能是50-70行)。
在旧的excel文件中,它包含大约169张纸,因此当您将169和50相乘时,新的Excel文件中将包含8450行
但是当我尝试执行代码时,结果将仅包含500行。 这是我正在尝试的代码
private void button2_Click(object sender, EventArgs e)
{
FileInfo fileInfo = new FileInfo("C:\\Documents\\testFile.xlsm");
string full = fileInfo.DirectoryName + "\\testResult.xlsx"; //Location for new Excel file that contain the result
xlApp = new Excel.Application();
xlWb = xlApp.Workbooks.Open("C:\\Documents\\testFile.xlsm");//Open the file
xlWS = xlWb.Sheets[xlWb.Sheets.Count];//Count the sheets
xlApp1 = new Excel.Application();
xlWb1 = xlApp1.Workbooks.Add();
int roww;//variable to save last number of row in the new excel file
for (int i = 2; i <xlWb.Sheets.Count; i++) // looping
{
xlWb.Sheets[i].Activate();
xlRange = xlWS.UsedRange;
row = xlRange.Rows.Count;
col = xlRange.Columns.Count;
xlWS1 = (Excel.Worksheet)xlWb1.Worksheets.get_Item(1);
xlRange1 = xlWS1.UsedRange;
roww = xlRange1.Rows.Count;
fulldata = new string[row][];
//for transfer data to temp variable
for (int j = 0; j < fulldata.Length; j++)
{
fulldata[j] = new string[col];
}
for(int k = 0 ; k<row;k++)
{
for (int l = 0; l < col; l++)
{
fulldata[k][l] = xlWS.Cells[k + 1, l + 1].value2.ToString();
}
}
//too export the data
if (roww == 1) //if to count how many roww there is in the new file, if there is no data then it just put the data from the first row
{
for (int k = 0; k <row; k++)
{
for (int l = 0; l < col; l++)
{
xlWS1.Cells[k + 1, l + 1] = fulldata[k][l];
}
}
}
else // if the file contain data from last sheet *means there will be more than 1 rows already fiiled
{
for (int k = 0; k < row; k++)
{
for (int l = 0; l < col; l++)
{
xlWS1.Cells[roww + 1, l + 1] = fulldata[k][l];
}
}
}
}
xlWb.Save();
xlWb.Close();
xlWb1.SaveAs(full, Excel.XlFileFormat.xlOpenXMLWorkbook, missing, missing,
false, false, Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
xlWb1.Close();
closeExcel(xlApp);
closeExcel(xlApp1);
}
预期结果是结果将有8450行,其中包含我要导出的多张纸中的数据
实际结果只有500行,也许有人可以更正我的代码,我不知道我在这里想念什么
答案 0 :(得分:0)
在上面的代码中,在for
循环内,在else
块内(如果新excel中的工作表已经有一些数据,则在其中添加值)
您正在设置:
xlWS1.Cells[roww + 1, l + 1] = fulldata[k][l];
在这里,您没有增加Cells
属性的行值。由于roww
在执行for
循环期间将包含相同的数据,因此您总是将数据写入同一行。
应该是
xlWS1.Cells[roww + k + 1, l + 1] = fulldata[k][l];