![](/img/trans.png)
[英]How do I check which cells belong to a merged cell and get the merged cell's value using c# Excel Interop?
[英]How do I get if a value of an excel cell is empty in C#
所以我正在制作一个简单的工作时间跟踪应用程序,它会扫描条形码以了解您何时登记入住,然后再次为退房,计算小时数,然后将它们保存在 a.xml 中。 问题是,它取决于一天的工作,但您可以每天多次入住和退房(例如,如果您在上午和下午工作)。 所以我需要代码来检查特定单元格的值是否为空,如果它只是保存小时数,如果它不是空的,它会获取单元格的值并添加在那段时间计算的新小时数。 我的代码如下。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace LCB
{
public partial class Form1 : Form
{
string name;
DateTime T_Entrada;
DateTime T_Salida;
TimeSpan Horas;
public float nhoras;
bool B_Entrada;
public Form1()
{
InitializeComponent();
B_Entrada = false;
textBox4.Text = B_Entrada.ToString();
}
//ESCIBIR EN EXCEL CODIGOO
public void WriteSample()
{
if (name == "Paco")
{
if(excelWorksheet.Cells[4,System.DateTime.Today.Day].Value2 == null)
{
excelWorksheet.Cells[4, System.DateTime.Today.Day].Value2 = nhoras;
}
else
{
excelWorksheet.Cells[4, System.DateTime.Today.Day].Value2 += nhoras;
}
excelApp.ActiveWorkbook.SaveAs(@"C:\Users\PRACTICVAS\Desktop\" + System.DateTime.Today.Month + ".xls", Excel.XlFileFormat.xlWorkbookNormal);
}
excelWorkbook.Close();
excelApp.Quit();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelWorksheet);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelWorkbook);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelApp);
GC.Collect();
GC.WaitForPendingFinalizers();
}
name 是一个字符串,现在用于检查每个不同的人,所以问题是,它不检查单元格值是否为 null,并且始终保存 nhoras 的新值,即每次结帐后的小时数。 有任何想法吗?
如果您想避免导航Range.Value
和Range.Value2
可以返回的所有各种值,只需阅读Text
属性会更容易。 它返回一个包含单元格可见内容的string
。 如果是空字符串,则单元格不包含值。 它永远不是 null。
if(excelWorksheet.Cells[4,System.DateTime.Today.Day].Text == string.Empty)
或者
if(excelWorksheet.Cells[4,System.DateTime.Today.Day].Text.Length == 0)
这是假设您正在检查的单元格永远不会包含返回空字符串的公式。
假设单元格包含
=""
然后.Text
属性将返回一个空字符串,但单元格并不是真正的空。 在您必须考虑到这一点的可能性很小的情况下,您还需要确保.Formula
属性也返回一个空字符串。
为简单起见,您可以编写一个 function ,如:
bool IsEmptyCell(Range cell)
{
return cell.Text.Length == 0 && cell.Formula.Length == 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.