如何读取excel文件并仅选择具有数据的单元格-不格式化,不空格,仅文本或数字。
我知道我可以这样阅读电子表格:如何仅对那些单元格执行“选择”并进行复制。预先感谢
Excel.Application excelApp = new Excel.Application();
if (excelApp != null)
{
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(@"C:\test.xls", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelWorkbook.Sheets[1];
Excel.Range excelRange = excelWorksheet.UsedRange;
int rowCount = excelRange.Rows.Count;
int colCount = excelRange.Columns.Count;
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
Excel.Range range = (excelWorksheet.Cells[i, 1] as Excel.Range);
string cellValue = range.Value.ToString();
//do anything
}
}
excelWorkbook.Close();
excelApp.Quit();
答案 0 :(得分:1)
使用现有的方法,您所缺少的是将值与string.empty进行比较,并且知道可以使用Excel.Application.Union来组合范围。
考虑此伪代码(也就是我没有运行它)。
请注意,如果您想提高精度(超出显示用户的excel格式),则应使用.Value2而不是.Value。
public void CopyValues()
{
Excel.Application excelApp = new Excel.Application();
if (excelApp != null)
{
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(@"C:\test.xls", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelWorkbook.Sheets[1];
Excel.Range excelRange = excelWorksheet.UsedRange;
int rowCount = excelRange.Rows.Count;
int colCount = excelRange.Columns.Count;
Excel.Range copyRange = null;
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
Excel.Range range = (excelWorksheet.Cells[i, j] as Excel.Range);
if (range.Value.ToString().Trim() != string.Empty)
{
if (copyRange == null)
{
copyRange = range;
}
else
{
//Its got somehting so union it in
copyRange = excelApp.Union(copyRange, range);
}
}
}
}
//Copy to clipboard
copyRange.Copy();
excelWorkbook.Close();
excelApp.Quit();
}
}