我有一個datagridview來顯示我的條目,我想打印出來就像一個Excel表。如何在C#中打印DataGridView?
有沒有什麼辦法可以完全打印datagridview,或者你建議用什麼樣的控件來存儲和打印數據?
或者如何在C#中使用HTML表格來幫助我創建和打印它們?
我有一個datagridview來顯示我的條目,我想打印出來就像一個Excel表。如何在C#中打印DataGridView?
有沒有什麼辦法可以完全打印datagridview,或者你建議用什麼樣的控件來存儲和打印數據?
或者如何在C#中使用HTML表格來幫助我創建和打印它們?
Here的解決方案。
首先,你要知道在.net庫中的類的PrintDocument,這個類可以幫助您打印任何矩形 ,你的任務是到表中轉換成的datagridview矩形(或繪製匹配了新的矩形datagridview中的表格大小包括繪圖字符串(這些字符串是單元格的內容)?)。之後,您可以使用類PrintDocument中的方法和更多來開始打印。
http://www.codeproject.com/KB/printing/printingdatagridview.aspx
你必須先加入CodeProject上的網絡能夠下載的示例代碼。
你能顯示一些代碼嗎? – hitautodestruct 2012-11-26 19:09:34
// make a function named zpt
int rw=dataGridView1.Rows.Count; //define rw as globly variable in form
public void zpt()
{
PrintDialog pd = new PrintDialog();
PrintDocument pdoc = new PrintDocument();
PrinterSettings ps = new PrinterSettings();
Font font = new Font("Arial", 10);
PaperSize psz = new PaperSize("Custom", 100, 200);
pd.Document = pdoc;
pd.Document.DefaultPageSettings.PaperSize = psz;
pdoc.DefaultPageSettings.PaperSize.Height = 820;
pdoc.DefaultPageSettings.PaperSize.Width = 700;
pdoc.PrintPage += new PrintPageEventHandler(pdoc_PrintPage);
DialogResult res = pd.ShowDialog();
if (res == DialogResult.OK)
{
PrintPreviewDialog prv = new PrintPreviewDialog();
prv.Document = pdoc;
res = prv.ShowDialog();
if (res == DialogResult.OK)
{
pdoc.Print();
}
}
}
void pdoc_PrintPage(object sender, PrintPageEventArgs e)
{
Graphics graphics = e.Graphics;
Font font = new Font("Courier New", 10);
float fontHeight = font.GetHeight();
int startX = 50;
int startY = 65;
int Offset = 40;
graphics.DrawString("Welcome to Bakery Shop", new Font("Courier New", 10), new SolidBrush(Color.Black), startX, startY + Offset);
Offset = Offset + 20;
string underLine = "------------------------------------------";
graphics.DrawString(underLine, new Font("Courier New", 10), new SolidBrush(Color.Black), startX, startY + Offset);
Offset = Offset + 20;
int a = dataGridView1.Rows.Count;
for (int i = 0; i < a; i++)
{
graphics.DrawString(Convert.ToString(dataGridView1.Rows[i].Cells[0].Value), new Font("Courier New", 10), new SolidBrush(Color.Black), startX, startY + Offset);
graphics.DrawString("\t"+Convert.ToString(dataGridView1.Rows[i].Cells[1].Value), new Font("Courier New", 10), new SolidBrush(Color.Black), startX, startY + Offset);
Offset = Offset + 20;
}
}
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.Rows.Add();
dataGridView1.Rows[rw].Cells[0].Value = textBox1.Text;
dataGridView1.Rows[rw].Cells[1].Value = textBox2.Text;
rw++;
}
private void button2_Click(object sender, EventArgs e)
{
// on print Button which is in your window for code this...
zpt();
}
Theres很多解決方案在線。你可以谷歌它 here
我知道你指出一篇文章說明問題的確切解決方案。但是,是否有可能進一步闡述並給出正確答案? – hitautodestruct 2012-11-26 19:05:53