这是我在C#中的第一个应用程序。
我正在尝试在Excel工作表中搜索“ ID”,并在地址标签上打印人员详细信息,然后将其已注册的人添加到Excel工作表(列P_Reg = 0尚未注册或已注册1)。>
最后,我可以打印出注册人员的名单。
要保存,请在每个人之后退出Excel,因为如果没有它,我将收到xlsx文件为只读的错误,则保存和退出工作正常,但搜索框有效,但只能运行一次。
示例:
当我第一次搜索时有效
但是当我第二次尝试时没有任何反应
我必须使用foreach
之类的东西吗?
public partial class Form2 : Form
{
public string fo
{
get { return textBox1.Text; }
set { label1.Text = value; }
}
public Form2()
{
InitializeComponent();
}
private void Form2_Load_1(object sender, EventArgs e)
{
Excel.Application xlApp = new Excel.Application();
string path = @"D:\Book1.xlsx";
Excel.Workbook workBook = xlApp.Workbooks.Open(path);
Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Worksheets["Sheet1"];
Excel.Range range = (Excel.Range)workSheet.Columns[1];//Range of Column A
Excel.Range findRange;
string strToFind = label1.Text;
string valueInColumnB;
string valueInColumnC;
// SEARCH
findRange = range.Find(strToFind);
if (findRange is null)
{
MessageBox.Show("id not found");
this.Close();
}
else
{
valueInColumnB = workSheet.Cells[findRange.Row, 2].value;
valueInColumnC = workSheet.Cells[findRange.Row, 3].Value;
// Register & SAVE
workSheet.Cells[findRange.Row, 4].value = "1";
xlApp.DisplayAlerts = false;
workBook.Save();
label2.Text = valueInColumnB;
label3.Text = valueInColumnC;
// PRINT
printDocument1.DefaultPageSettings.Landscape = true;
var pd = new PrintDocument();
pd.PrintPage += (s, ev) =>
{
var bmp = new Bitmap(800, 800);
this.DrawToBitmap(bmp, new Rectangle(Point.Empty, this.Size));
ev.Graphics.DrawImageUnscaled(bmp, ev.MarginBounds.Location);
ev.HasMorePages = false;
};
PaperSize ps = new PaperSize("", 170, 350);
var dlg = new PrintPreviewDialog();
dlg.Document = pd;
pd.PrintController = new StandardPrintController();
pd.DefaultPageSettings.Margins.Left = 0;
pd.DefaultPageSettings.Margins.Right = 0;
pd.DefaultPageSettings.Margins.Top = 20;
pd.DefaultPageSettings.Margins.Bottom = 0;
pd.DefaultPageSettings.PaperSize = ps;
pd.Print();
this.Close();
xlApp.Quit();
}
}
}