C#中导出到Excel中的数据居中显示并且要显示字段名称!
麻烦大家帮我看一下下面这个关于C#中把查询出来的数据导出到Excel里边,并且进行打印,以下代码即可实现导出到Excel里面,但是没有显示字段名称,直接就把数据给显示出来了,我是想让导出到Excel里面的数据居中显示,并且把字段的名称也显示出来,以下代码在那些地方需要进行修改,以能够满足以上要求,请各位高手指点,小弟在此表示衷心感谢!
private void excelToolStripMenuItem_Click_1(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = false;
saveFileDialog.Title = "导出Excel文件到";
if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
return;
Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312")); //gb2312
try
{
//写标题
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
if (i == 0) dataGridView1.Columns[i].HeaderText = "序号";
if (i > 0)
{
std += "\t";
}
std += dataGridView1.Columns[i].HeaderText;
}
sw.WriteLine(str);
//写内容
for (int j = 0; j < dataGridView1.Rows.Count - 1; j++)
{
tempStr = "";
for (int k = 0; k < dataGridView1.Columns.Count; k++)
{
if (k == 0 && j < (dataGridView1.Rows.Count - 2))
dataGridView1.Rows[j].Cells[k].Value = j + 1;
if (k > 0)
{
tempStr += "\t";
}
tempStr += dataGridView1.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
private void 导出ExcelToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = false;
saveFileDialog.Title = "导出Excel文件到";
if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
return;
Stream myStream;
myStream = saveFileDialog.OpenFile();