我试图导出包含多张工作表的 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 行,也许有人可以纠正我的代码,我不知道我在这里错过了什么
在上面的代码中,在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];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句