c# - C# Excel - 仅读取/选择具有值/数据的单元格
问题描述
如何读取 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();
解决方案
使用您现有的方法,您缺少的是将值与 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();
}
}
推荐阅读
- jquery - 我使用 jquery 无法获取 html p 元素文本
- javascript - 将 React 组件添加到 PDF 而不将其放在 dom 中
- java - 如何根据多个变化对对象的 ArrayList 进行排序
- node.js - 如何使设置的标头在 Express Node JS 中保持不变
- laravel-5.8 - Laravel 5.8 在创建方法期间访问新的行 ID
- node.js - 网站打开时未调用 app.get('/')
- javascript - 这个 javascript 替代文本微调器是如何工作的
- html - 如何将垂直滚动条添加到第一列始终固定的表中
- spring-boot - UserDetailsService 被安全配置忽略
- java - 如何将数组中的数据写入文本文件?